Get query string values when submitting a form…MVC

2019-06-23 17:17发布

问题:

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

回答1:

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.



回答2:

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



回答3:

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"];

}