Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get query string values when submitting a form...MVC3

In my MVC3 app, if i type in a query string value in the url and hit enter, I can get the value i typed:

localhost:34556/?db=test

My default action which will fire:

public ActionResult Index(string db)

The variable db has "test" in it.

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

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

And the following is the form i'm sending:

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

Heres the action:

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

The variable dbName is null because Request.QueryString["db"] is null, so is the variable db being passed in and i dont know why. Can someone help me get a query string variable after a form is submitted? Thanks

like image 763
BoundForGlory Avatar asked Jul 09 '12 20:07

BoundForGlory


3 Answers

You could 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 (i.e) string test = dbName;
        //Do whatever you want here. Perhaps a redirect?
    }
    return View(lovm);
}

ViewModel:

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

Edit: Fixed it up for your requirement.

like image 86
Saedeas Avatar answered Nov 13 '22 03:11

Saedeas


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

like image 3
ThiefMaster Avatar answered Nov 13 '22 03:11

ThiefMaster


As @ThiefMaster♦ said, in a POST you cannot have the query string, never the less if you don't wan't to serialize your data to an specific object you can use the FormCollection Object which allows you to get all the form elements pass by post to the server

For example

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

}
like image 2
Jorge Avatar answered Nov 13 '22 03:11

Jorge