【问题标题】:MVC 5 model properties null when ajax form submitted提交ajax表单时MVC 5模型属性为空
【发布时间】:2014-11-16 17:04:50
【问题描述】:

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

控制器和模型

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;
    }
}

局部视图

@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>
}

看完this post我换了

public PartialViewResult Index(TestModel model){}

public PartialViewResult Index(FormCollection model)
{
    var val = model["SomeFieldName"];
    var otherVal = model["OtherFieldName"];
}

我能够通过 FormCollection 访问这些值,但我无法将它们放入我的模型中。关于是什么让我的模型无法正确填充的任何想法?

【问题讨论】:

    标签: jquery ajax asp.net-mvc-5


    【解决方案1】:

    你的属性需要getter和setter

    public string SomeFieldName { get; set; }
    public string OtherFieldName { get; set; }
    

    由于您的方法签名是public PartialViewResult Index(TestModel model)DefaultModelBinder 会初始化TestModel 的新实例,然后尝试根据发布的值设置其属性的值,但由于您的属性没有设置器,因此无法这样做。

    【讨论】:

    • 我一直在用头撞屏幕,试图弄清楚这一点。非常感谢!
    【解决方案2】:

    你需要修改你的模型类如下

    public class TestModel
    {
        [Required]
        public string SomeFieldName {get; set;}
        [Required]
        public string OtherFieldName {get; set;}
    }
    

    现在为什么它使用 FormCollection 而不是测试模型。

    当您请求 formcollection 时,您将获得提交给 post 方法的所有表单字段,这就是您可以访问表单中所有字段的原因。

    当您提到特定的类 TestModel 时,我们会看到称为 模型绑定 的东西,它会尝试将提交的值与模型的属性进行映射。标记属性一词,因为属性将具有 get 和 set 方法。如果找到 set 属性,则模型绑定器将成功映射和替换模型中的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多