Home > Net >  Pass data from controller to View with redirect method
Pass data from controller to View with redirect method

Time:03-09

I have an ASP.Net web application in C# in which I want to show some visualizations graphs in my report.cshtml View.
For the moment, I'm using the httpget function of my report.cshtml View to past the data to my View. But with this method, I can't filter the data. So this is what I want to do :

When an user connect in my website, it launch my Httppost function inside my HomeController, with the username & password as arguments.
I use this function to redirect to my report.cshtml View with the response.redirect method, in which the user will should his personnal data as visualizations.

My database is stored locally in a variable named my_list which I can use in my httppost function.

What I want is to past this list to the js section of my report.cshtml when the redirection occurs. Is this possible by using the redirect method?
Or, if not, is there another solution to do it ?

My Index.cshtml :


<form method="post" , enctype="multipart/form-data">

            <input required id="my_pseudo" name="my_pseudo" v-model="pseudo" placeholder="Username" />
            <input required id="my_password" name="my_password" type="password" v-model="password" placeholder="password" />

            <Button id="test_click" Text="Connexion">Connection</Button>

        </form>

My httpget function :

public ActionResult EmbedReport()
        {

            List<Dashboard___Veins_Data___By_Institution> my_list = fct_BO.Class1.My_function("my_user");
            // It's at this moment that the filter is applied, so I want that, instead of "my_user", I can put a variable which is the "Contact_name" of the user currently connected.
            ViewBag.Message = my_list;


            return View();
        }

My httppost function

public ActionResult Index(string my_pseudo, string my_password)
        {
            
            
            
            //It's not good for the moment, but it's here that I want to see if "my_pseudo" and "my_password" match a line of my table "User_connection". If yes, the redirect method occurs and I would like to past my list at the same time ->

             if (...)
                  Response.Redirect("~/Home/Report");
                  

            // If not, then the user will receive an error message.
             else
                Response.Write("<script>alert('Login or password incorrect')</script>");

            return View();
            
        }

I didn't finish this function, because my table "User_connection", in my database, is not finished for the moment.

Also, somebody adviced me to use RedirectResult instead of response.redirect. Is it a better solution?

Thanks.

CodePudding user response:

May I suggest that you wrap your behaviour in interfaces?

so that you have an Interface

public interface IErrorHandler {
   void provideErrorResponse(HttpResponse response);
}

and

public interface ISuccessHandler {
   void provideSuccessfulResponse(HttpResponse response);
}

Because now you can implement small single purpose classes that process a correct or incorrect response a certain way, meaning if you need to error handle more than one result the same way (VERY LIKELY) you can simply dependency inject the error handler into your other controllers as well, and only have 1 set of tests for the interface, instead of a suite of tests to test the same behaviour on each controller.

In terms of your final question:

"

Response.Redirect("http://www.microsoft.com/gohere/look.htm");

Calling Redirect is equivalent to calling Redirect with the second parameter set to true.

Redirect calls End which throws a ThreadAbortException exception upon completion. This exception has a detrimental effect on Web application performance. Therefore, we recommend that instead of this overload you use the HttpResponse.Redirect(String, Boolean) overload and pass false for the endResponse parameter, and then call the CompleteRequest method. For more information, see the End method."

Taken from: https://docs.microsoft.com/en-us/dotnet/api/system.web.httpresponse.redirect?view=netframework-4.8

That is likely why he recommended you not use it. but this is a total guess, as I cannot know what "somebody" was referencing at the time :)

As an example:

public class HomeController {
   private IErrorHandler _errorHandler;
   private ISuccessHandler _successHandler; 

   public class HomeController (IErrorHandler errorHandler, ISuccessHandler successHandler)
   {
      _errorHandler = errorHandler;
      _successHandler = successHandler;
   }

   public ActionResult Index(string my_pseudom, string my_password)
   {
      if (...)
         _successHandler.provideSuccessfulResponse(Response);
                  
      // If not, then the user will receive an error message.
      else
         _errorHandler.provideErrorResponse(Response));
   }

}

Notice that you can even re-use successful responses provided they don't have a difference in how a success response should be handled (Less likely)

for purpose of "filtering" your view, that is usually done via the end-point to back-end by passing a set of parameters from your view, to the controller, then to the back-end, and then the resulting list of items, will be filtered at the back-end and provided back as a response.

So when you say you wish to accomplish this via re-direct I am not sure I completely follow what you intended to do?

Something like this?

public interface ILoginHandler {
   ILoginResult HandleLogin(string username, string password); 
}

public inteface ILoginResult {
   bool WasValid {get;set;}
}

public class HomeController {
       private IErrorHandler _errorHandler;
       private ISuccessHandler _successHandler; 
       private ILoginHandler _loginHandler;
    
       public class HomeController(IErrorHandler errorHandler, ISuccessHandler successHandler, ILoginHandler loginHandler)
       {
          _errorHandler = errorHandler;
          _successHandler = successHandler;
          _loginHandler = loginHandler;
       }
    
       public ActionResult Index(string my_pseudom, string my_password)
       {    
          ILoginResult loginResult = _loginHandler.HandleLogin(my_pseudom, my_password);
          if (loginResult.WasValid)
             _successHandler.provideSuccessfulResponse(Response);
          else
             _errorHandler.provideErrorResponse(Response));
       }
    
    }

based on who logs in, you could make a factory pattern, that takes the username, and then provides a specific request to your back-end and returns the list you want, if you want filtering, provide the filtering values as part of the URL, or make it a post, so you can provide parameters that way.

And then update your factory to use these parameters also. Shouldn't be a problem then at all.

  • Related