提交表单时获取查询字符串值… MVC3

在我的MVC3应用程序中,如果我在URL中键入查询字符串值并按Enter键,我可以获得我输入的值:

localhost:34556/?db=test 

我的默认操作将触发:

 public ActionResult Index(string db) 

变量db中有“test”。

现在,我需要提交一个表单并读取查询字符串值,但是当我通过jQuery提交表单时:

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

以下是我发送的表格:

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

inheritance人的行动:

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

变量dbName为null,因为Request.QueryString [“db”]为null,因此传入的变量db也是如此,我不知道为什么。 在提交表单后,有人可以帮我获取查询字符串变量吗? 谢谢

你可以有类似的东西

控制器:

 [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); } 

视图模型:

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

编辑:根据您的要求修复它。

由于您正在使用POST,因此您要查找的数据位于Request.Form而不是Request.QueryString

正如@ ThiefMaster♦所说,在POST中你不能拥有查询字符串,如果你不想将数据序列化为特定对象,你可以使用FormCollection Object ,它可以让你获得所有表单元素通过邮件传递给服务器

例如

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