模型如何使用Asp.net控制器Model

时间:2016-04-12 15:29:17

标签: javascript c# asp.net ajax asp.net-mvc

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

1 个答案:

答案 0 :(得分:4)

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