模型如何将Javascript FormData与Asp.net Controllers模型绑定

How model bind Javascript FormData with Asp.net Controllers Model

本文关键字:模型 Asp net Controllers 绑定 FormData Javascript      更新时间:2024-05-11

是否可以将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");
    }

当您将FormData对象与ajax一起使用时,数据将以multipart/form-data的形式发送,并且会自动为您设置具有正确边界的内容类型标头
您可以覆盖内容类型,并将tit设置为您想要的任何内容,这就是这里的情况
你可能会想,我没有这么做,你的好朋友jQuery是为你做的。它为您设置了$.ajax(application/x-www-form-urlencoded)的默认内容类型,这几乎会破坏请求
要停止此操作,即停止jQuery设置内容类型标头,必须将contentType参数设置为false。