0

我无法理解为什么在发布表单时我的模型没有连同它的值一起传递给我的控制器。

我有一个从 web 服务中获取的强类型模型 (UnitContract) 的视图,该模型包含一组值。在我的操作中,我试图获取模型中存在的 int ID 和 bool Disabled 字段。调试时,我看到从表单传递的模型根本不包含任何值。我错过了什么?

我的观点(UnitContract 作为强类型模型):

...
<form class="pull-right" action="~/UnitDetails/EnableDisableUnit" method="POST">
        <input type="submit" class="k-button" value="Enable Unit"/>
    </form>

我的控制器动作:

[HttpPost]
public ActionResult EnableDisableUnit(UnitContract model)
{
    var client = new UnitServiceClient();
    if (model.Disabled)
    {
        client.EnableUnit(model.Id);
    }
    else
    {
        client.DisableUnit(model.Id);
    }

    return RedirectToAction("Index", model.Id);
}
4

4 回答 4

4

听起来您需要将模型中的字段添加到表单中。假设您的视图接受 UnitContract 模型,那么这样的事情应该可以工作:

<form class="pull-right" action="~/UnitDetails/EnableDisableUnit" method="POST">
    @Html.HiddenFor(x => x.Id)
    @Html.HiddenFor(x => x.Disabled)
    <input type="submit" class="k-button" value="Enable Unit"/>
</form>

现在,当您提交表单时,它应该将字段提交给您的模型。

于 2013-04-30T12:57:20.050 回答
2

MVC 框架将使用表单中的数据来创建模型。由于您的表单本质上是空的,因此没有数据可用于创建模型,因此您获得了一个没有填充任何数据的对象。

当您发布表单时,在请求中从浏览器发送的唯一数据是表单内的数据。您必须将模型中属性的数据作为表单中的字段放置,以便有一些东西可以填充模型。

于 2013-04-30T12:55:36.227 回答
2

研究使用@Html.HiddenFor(). 将这些放入您的表单中,您希望看到的数据会发送回您的控制器。例如,您的表单看起来像...

<form class="pull-right" action="~/UnitDetails/EnableDisableUnit" method="POST">
    @Html.HiddenFor(x => x.Id)
    @Html.HiddenFor(x => x.IsDisabled)
    <input type="submit" class="k-button" value="Enable Unit"/>
</form>
于 2013-04-30T12:58:01.117 回答
0

假设您有这样的模型:

public class UnitContract
{
    public int Id { get; set; }
    public DateTime SignedOn { get; set; }
    public string UnitName { get; set; }
}

您的视图将如下所示:

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

    <fieldset>
        <legend>UnitContract</legend>

        @Html.HiddenFor(model => model.Id)

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

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

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

在您的控制器中:

    [ValidateAntiForgeryToken]
    [HttpPost]
    public ActionResult Edit(UnitContract unitContract)
    {
        // do your business here .... unitContract.Id has a value at this point
        return View();
    }

希望这会有所帮助。

于 2013-04-30T13:04:32.800 回答