Skip to main content
 首页 » 编程设计

javascript之模型如何将 Javascript FormData 与 Asp.net Controller 模型绑定(bind)

2024年02月05日43bhlsheji

是否可以自动将 ASP.NET Controller 模型与提交数据为 FormData 的 ajax 请求绑定(bind)? .

在我提供的示例中,我需要使用 HttpContext.Current.Request.Form["property_name"] 接收数据,因为如果我提供与提交的表单数据相同的模型,所有值都等于 null;

或者 ASP.NET 模型绑定(bind)是否仅适用于 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> 

Controller :

    [HttpPost] 
    public ActionResult TestPost() 
    { 
        var firstname = HttpContext.Current.Request.Form["firstName"]; 
        var lastName =  HttpContext.Current.Request.Form["lastName"]; 
        return PartialView("TestPost"); 
    } 

Controller 不工作:

   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 发送,并且内容类型 header 会自动为您设置正确的边界。
您可以覆盖内容类型并将 tit 设置为您想要的任何内容,这就是此处发生的情况。
你可能会想我没有这样做,好吧你的好 friend jQuery 为你做了。它为您设置了 $.ajax 的默认内容类型 (application/x-www-form-urlencoded),这几乎会破坏请求。
要停止此操作,即停止 jQuery 设置内容类型 header ,您必须将 contentType 参数设置为 false。