隐藏的ViewModel属性在null时默认为0 - 应保持为null

时间:2013-02-17 19:01:43

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

获取控制器方法:

    public ActionResult Create(int? parentId)
    {
        var model = new CreatePersonViewModel();

        // pull set from db
        var parent = _db.Persons.FirstOrDefault(s => s.PersonId == parentId);

        if (parent != null)
        {
            model.ParentId = parent.PersonId;
        }

        return View("Create", model);
    }

POST:

public ActionResult Create(CreatePersonViewModel viewModel) // viewModel.ParentId is 0 when it's passed to this method from the view, even though I didn't set it, and it's null coming from GET.  
        {
            //bla bla
        }

我的观点:

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>CreatePersonViewModel</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        @Html.HiddenFor(model => model.ParentId) // tried with second parameter of "null" as well

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

任何想法为什么视图在该属性中发送值为0时应该为null的情况?我没有在这里添加任何细节,但表单验证要求更多文本,所以在这里。

0 个答案:

没有答案