提交ajax表单时,MVC 5模型属性为null

ell*_*t-j 1 ajax jquery asp.net-mvc-5

我创建一个模型并将其传递给局部视图.当我提交模型ModelStat.IsValid为true时,无论我在表单上输入什么值,其属性都为null.

控制器和型号

public class TestController : Controller
{
    // GET: Test
    public ActionResult Index()
    {
        TestModel model = new TestModel();
        model.SomeFieldName= "Test";
        model.OtherFieldName = "AnotherTest";
        return PartialView(model);
    }
    [HttpPost]
    public PartialViewResult Index(TestModel model)
    {
        if(ModeState.IsValid)
        {
            //Do Stuff to model
        }
        return PartialView(model);
    }
    public class TestModel
    {
        [Required]
        public string SomeFieldName;
        [Required]
        public string OtherFieldName;
    }
}
Run Code Online (Sandbox Code Playgroud)

局部视图

@model Portal.Controllers.TestController.TestModel
@using (Ajax.BeginForm("Index", new AjaxOptions { UpdateTargetId = "Content" }))
{
    @Html.ValidationSummary(true)
    <div id="Content">
       @Html.LabelFor(model => model.SomeFieldName,"FieldName")
       @Html.TextBoxFor(model => model.SomeFieldName)
       @Html.LabelFor(model => model.OtherFieldName ,"OtherFieldName")
       @Html.TextBoxFor(model => model.OtherFieldName )
       <input type="submit" value="Save" class="btn btn-default" />

    </div>
}
Run Code Online (Sandbox Code Playgroud)

看完这篇文章后,我换了

public PartialViewResult Index(TestModel model){}
Run Code Online (Sandbox Code Playgroud)

public PartialViewResult Index(FormCollection model)
{
    var val = model["SomeFieldName"];
    var otherVal = model["OtherFieldName"];
}
Run Code Online (Sandbox Code Playgroud)

我能够通过FormCollection访问值,但我无法将它们放入我的模型中.有什么想法让我的模型不能正确填充?

小智 6

您需要在您的属性上使用getter和setter

public string SomeFieldName { get; set; }
public string OtherFieldName { get; set; }
Run Code Online (Sandbox Code Playgroud)

当你的方法签名是public PartialViewResult Index(TestModel model)DefaultModelBinder初始化的新实例TestModel,然后尝试设置基础上,公布值的属性的值,但不能这样做,因为你的属性没有setter方法.