Get string values ​​of a request when submitting a form ... MVC3

In my MVC3 application, if I type the value of the query string in url and press enter, I can get the value entered:

localhost:34556/?db=test 

My default action that will fire:

 public ActionResult Index(string db) 

There is a β€œtest” in the db variable.

Now I need to submit the form and read the value of the query string, but when I submit the form via jQuery:

  $('#btnLogOn').click(function(e) { e.preventDefault(); document.forms[0].submit(); }); 

And the following form that I submit:

  @using (Html.BeginForm("LogIn", "Home", new { id="form1" }, FormMethod.Post)) 

Here is the action:

  [HttpPost] public ActionResult LogIn(LogOnModel logOnModel, string db) { string dbName= Request.QueryString["db"]; } 

The value of the dbName variable is null because Request.QueryString ["db"] is null, so the db variable is passed, and I don’t know why. Can someone help me get the query string variable after submitting the form? Thanks

+4
source share
3 answers

You might have something like

Controllers

 [HttpGet] public ActionResult LogIn(string dbName) { LogOnViewModel lovm = new LogOnViewModel(); //Initalize viewmodel here Return view(lovm); } [HttpPost] public ActionResult LogIn(LogOnViewModel lovm, string dbName) { if (ModelState.IsValid) { //You can reference the dbName here simply by typing dbName (ie) string test = dbName; //Do whatever you want here. Perhaps a redirect? } return View(lovm); } 

ViewModel:

 public class LogOnViewModel { //Whatever properties you have. } 

Edit: This is fixed for your requirement.

+3
source

Since you are using POST, the data you are looking for is in Request.Form instead of Request.QueryString .

+2
source

As @ThiefMaster ♦ said, in POST you cannot have a query string, however, if you do not want to serialize your data to a specific object, you can use the FormCollection Object , which allows you to get all form elements that are mailed to the server

for instance

 [HttpPost] public ActionResult LogIn(FormCollection formCollection) { string dbName= formCollection["db"]; } 
+1
source

All Articles