asp.net MVC表单未发布参数值 [英] asp.net mvc form not posting parameter values
问题描述
我正在解决我认为是一个非常愚蠢的问题,显然我缺少简单的东西.
I'm hitting what I think is a pretty stupid issue that I am obviously missing something simple on.
我创建了一个简单的asp.net mvc网站(.net 4.5),并将索引更改为一种简单的形式,我想将其发布回自身并吐回变量.
这是我的表格
I made a simple asp.net mvc site (.net 4.5) and changed the index to have a simple form that I'd like to just post back to itself and spit back the variables.
here is my form
@using(Html.BeginForm())
{
<input type="text" class="form-control" id="empId" placeholder="Enter EmployeeId (ex. 999999)">
<input type="text" class="form-control" id="account" placeholder="Enter account)">
<input type="email" class="form-control" id="email" placeholder="Enter email">
<input type="submit" class="btn btn-default" value="Submit" />
}
这是我的发布方法
[HttpPost]
public ActionResult Index(string empId, string account, string email)
{
return Content(Request["empId"]);
}
页面发布后我什么也没回来.同样在调试器中,我可以看到该方法被命中,但是即使我填写了表格,所有参数都为空.
I get nothing back when the page posts. Also in the debugger I can see that the method gets hit, however all the parameters are null even though I filled in the form.
我缺少明显的东西吗?
推荐答案
您只是忘记了name属性:
You just forget the name attribute:
@using(Html.BeginForm())
{
<input type="text" class="form-control" name="empId" id="empId" placeholder="Enter EmployeeId (ex. 999999)">
<input type="text" class="form-control" name="account" id="account" placeholder="Enter account)">
<input type="email" class="form-control" name="email" id="email" placeholder="Enter email">
<input type="submit" class="btn btn-default" value="Submit" />
}
我总是建议使用模型绑定而不是某些字符串或整数.如果使用得当,它将使模型绑定工作变得轻松:
I always recommend to use model binding instead of some strings or int. If you use them well, it will make the model binding work effortlessly:
型号:
public class ExampleModel
{
public int empId { get; set; }
public string account{ get; set; }
public string email{ get; set; }
}
在剃刀"页面中:
@using(Html.BeginForm())
{
@Html.EditorFor((m => m.intempId, new { @class = "form-control" } ))
@Html.EditorFor((m => m.account, new { @class = "form-control" }))
@Html.EditorFor((m => m.email, new { @class = "form-control" }))
}
,然后在控制器中:
[HttpPost]
public ActionResult Index(ExampleModel model)
{
return Content(model.empId);
}
使用模型,您还可以直接在模型上添加验证等,然后ASP.NET MVC可以将验证放在带有jQuery验证的前端和后端(如果是(ModelState.IsValid))中.使用模型有很多好处!
With the model, you can also add validation and so on, directly on the model and then ASP.NET MVC can put validation in both front-end with jQuery validation and back-end (if (ModelState.IsValid)). Lots of benefits to use models!
这篇关于asp.net MVC表单未发布参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!