模型中对象的MVC属性在post上为null

时间:2017-07-18 14:47:44

标签: c# asp.net-mvc razor

我知道有很多类似的帖子,但经过多次调查后我似乎无法找到答案。在回发后,CompanySetting.NewSetting.SettingType和CompanySetting.NewSetting.SettingValue为null,尽管将文本放入TextBoxFor字段并单击提交。 这是为什么?

以下是观点:

@model Project.Models.CompanySettingView
@using (Html.BeginForm())
                {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        <form>
            <div class="form-group">
             <label>Setting Type</label>
             @Html.TextBoxFor(m => m.NewSetting.SettingType, new { @class = "form-control", @id = "SettingType" })

            <br />

             <label>Setting Value</label>
             @Html.TextBoxFor(m => m.NewSetting.SettingValue, new { @class = "form-control", @id = "SettingValue" })

            <br />
          </div>
            <div style="float: right;">
            <button type="button" style="width:100px;" onclick="ClearFields()" class="btn btn-default">Clear</button>
            <button type="submit" style="width:100px;" class="btn btn-primary">Submit</button>
           </div>
         </form>
                }

接收控制器:

 [HttpPost]
public ActionResult AddCompanySetting(CompanySettingView model)
{
...
}

CompanySettingView类:

public class CompanySettingView
{
    public List<CompanySetting> Settings = new List<CompanySetting>();
    public CompanySetting NewSetting = new CompanySetting();
}

公司设置类:

 public class CompanySetting
 {
     public int CompanySettingId { get; set; }
     public int CompanyId { get; set; }
     public string SettingType { get; set; }
     public string SettingValue { get; set; }
 }

1 个答案:

答案 0 :(得分:2)

来自评论的回答

它与CompanySettingView中的对象初始化器有关。将它们更改为属性并在构造函数中初始化它们(确保该类具有默认构造函数)并且所有都应该是黄色的

这样的事情:

public class CompanySettingView
{
    public List<CompanySetting> Settings { get; set; }
    public CompanySetting NewSetting { get; set; }

    public CompanySettingView()
    {
        this.Settings = new List<CompanySetting>();
        this.NewSetting = new CompanySetting();
    }
}