【发布时间】:2016-04-12 15:29:17
【问题描述】:
是否可以将 ASP.NET 控制器模型与提交数据为 FormData 的 ajax 请求自动绑定。
在我提供的示例中,我需要使用 HttpContext.Current.Request.Form["property_name"] 接收数据,因为如果我提供与提交的表单数据相同的模型,则所有值都等于 null;
还是 ASP.NET 模型绑定仅适用于 JSON 请求?
简单代码如下:
查看:
@using (Html.BeginForm("Post", "Test", FormMethod.Post, new { @class="test-form"}))
{
<input type="text" name="firstName"/>
<input type="text" name="lastName"/>
<button type="submit">Submit</button>
}
脚本:
<script>
$('.test-form').on('submit', function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "@Url.Action("TestPost", "Test")",
method: "POST",
data: formData,
processData: false,
success: function(e){
}
});
});
</script>
控制器:
[HttpPost]
public ActionResult TestPost()
{
var firstname = HttpContext.Current.Request.Form["firstName"];
var lastName = HttpContext.Current.Request.Form["lastName"];
return PartialView("TestPost");
}
不工作的控制器:
public class User
{
public string firstName { get; set; }
public string lastName { get; set; }
}
[HttpPost]
public ActionResult TestPost(User model) //model values are null
{
return PartialView("TestPost");
}
【问题讨论】:
-
使用 Ajax.BeginForm 了解更多信息,请查看此链接hanselman.com/blog/ASPNETMVCPreview4UsingAjaxAndAjaxForm.aspx
-
你忘了
ContentType: false, -
@rashfmnb 如果我的 ajax 请求在 js 文件中怎么办?
-
@Musa 确实成功了,太棒了。小心解释为什么/如何?(我会尝试自己用谷歌搜索,但是..)
标签: javascript c# asp.net ajax asp.net-mvc