使用Html.BeginForm()ASP.NET MVC,Model为null

时间:2014-10-02 11:54:27

标签: asp.net-mvc html-helper

我遇到了以下问题:
用户访问网站,点击"添加"然后它发送回Controller,模型被检索并再次发送到View。在内部视图中,我检查Model是否为null 并显示数据。

@if (Model != null)
    {
        <div id="appInfo">
            <table>
                <tr>
                    <th>@Html.DisplayNameFor(x => Model.tytul)</th>
                    <th>@Html.DisplayNameFor(x => Model.kategoria.nazwa)</th>
                    <th>@Html.DisplayNameFor(x => Model.liczba_ocen)</th>
                    <th>@Html.DisplayNameFor(x => Model.avg_ocena)</th>
                    <th>@Html.DisplayNameFor(x => Model.typ)</th>
                </tr>
                <tr>
                    <td>@Model.tytul</td>
                    <td>@ViewData["kategoria"]</td>
                    <td>@Model.liczba_ocen</td>
                    <td>@Model.avg_ocena</td>
                    <td>@Model.typ</td>
                </tr>
            </table>
        </div> 
 <div>
                @using (Html.BeginForm("Confirm", "Wydawca", new { app = @Model }))
                {
                    <input type="submit" value="Cofirm it" />
                }
            </div>

在结束按钮&#34;确认&#34;已创建,单击它后会调用Confirm Method,但app变量始终为null。如果我将其值设置为除模型之外的任何值。

    [HttpPost]
    public ActionResult Confirm(aplikacja app)
    {
        ...
    }

创建按钮&#34;确认&#34;模型不为空,我查了一下。你碰巧知道出了什么问题吗?

生成的html

   <form action="/Wydawca/Confirm?app=Adds.Models.aplikacja" method="post">      
   <input type="submit" value="Zatwierdź" />

2 个答案:

答案 0 :(得分:5)

Html.BeginForm应该包裹所有输入元素,或者没有任何内容可以发布。将您的观点更改为:

@if (Model != null)
{
    @using (Html.BeginForm("Confirm", "Wydawca", new { app = @Model }))
    {
        <div id="appInfo">
            <table>
                <tr>
                    <th>@Html.DisplayNameFor(x => Model.tytul)</th>
                    <th>@Html.DisplayNameFor(x => Model.kategoria.nazwa)</th>
                    <th>@Html.DisplayNameFor(x => Model.liczba_ocen)</th>
                    <th>@Html.DisplayNameFor(x => Model.avg_ocena)</th>
                    <th>@Html.DisplayNameFor(x => Model.typ)</th>
                </tr>
                <tr>
                    <td> @Model.tytul</td>
                    <td>@ViewData["kategoria"]</td>
                    <td>@Model.liczba_ocen</td>
                    <td>@Model.avg_ocena</td>
                    <td>@Model.typ</td>
                </tr>
            </table>
        </div> 
        <div>
            @Html.HiddenFor(x => Model.tytul)
            @Html.HiddenFor(x => Model.kategoria.nazwa)
            @Html.HiddenFor(x => Model.liczba_ocen)
            @Html.HiddenFor(x => Model.avg_ocena)
            @Html.HiddenFor(x => Model.typ)
            <input type="submit" value="Cofirm it" />
        </div>
    }
}

答案 1 :(得分:2)

您正在尝试将对象(@Model)作为路由参数(app)传递。路由参数应包含标量值(int,string等),而不是对象。在浏览器中查看生成的HTML源代码,查看<form action="">的设置方式。然后回顾model binding的概念。

相关问题