我正在构建一个Web应用程序,我需要在按钮单击时传递给控制器的文本框的值。根据用户角色,我需要重定向到不同的页面。以下是我的代码。
查看:
@model namespace.ViewModels.LoginVM
@{
ViewBag.Title = "Login";
}
<h1>User Login</h1>
@using (Html.BeginForm("Login", "Login", FormMethod.Post))
{
<br />
<div style="background-color: skyblue; width: 50%">
<div style="padding-left: 1em">
<div class="display-label" style="font-size: large">
Enter User Info<br />
<br />
</div>
<div>
<div class="editor-label">@Html.LabelFor(model => model.empID)</div>
<div class="editor-field">@Html.TextBoxFor(model => model.empID)
@Html.ValidationMessageFor(model => model.empID)
</div>
<br />
</div>
<br />
<div>
<input id="submit" type="submit" value="Submit" />
</div>
</div>
</div>
<br />
}
控制器:
public class LoginController : Controller
{
[HttpPost]
public ActionResult Login()
{
MySQL msql = new MySQL();
// var empID= *how do I get empID on submit from View?* ;
var role = msql.Select("Select `role` from empDB where `eID` = '" + empID+ "'");
//if(role = "admin") { return RedirectToAction("Home"); }
//else {return View(); }
}
}
型号:
public class LoginVM
{
[Required(ErrorMessage = "Required!")]
[DisplayName("empID")]
public int empID{ get; set; }
}
答案 0 :(得分:0)
如果要在表单提交上获取表单字段值,可以向表单提交的操作方法添加与输入字段同名的参数。
由于您的输入字段名称属性值为"empID"
(检查页面的查看源),您可以为同名方法添加一个参数
[HttpPost]
public ActionResult Login(int empID)
{
//Check the value of empID parameter.
// For you to understand, I replaced your code with a line
// which basicaly return the value of this parameter value back
// to the client with a string "Received".
return Content("Received "+ empID);
}
现在我看到你有一个视图模型,其属性的名称与我们添加的参数相同。在这种情况下,您可以使用该类作为参数。
[HttpPost]
public ActionResult Login(LoginVM model)
{
//Check the value of model.empID parameter value.
return Content("Received "+ model.empID);
}
提交表单时,模型绑定器会将发布的表单数据映射到LoginVM
类对象的属性。
答案 1 :(得分:0)
您只需将视图模型添加为Post动作的参数
public class LoginController : Controller
{
[HttpPost]
public ActionResult Login(LoginVM model)
{
MySQL msql = new MySQL();
// var empID= *how do I get empID on submit from View?* ;
var role = msql.Select("Select `role` from empDB where `eID` = '" + model.empID + "'");
//if(role = "admin") { return RedirectToAction("Home"); }
//else {return View(); }
}
}