如何在与POST一起使用的输入中设置文本?

时间:2012-11-09 19:21:07

标签: c# asp.net-mvc asp.net-mvc-3 razor

当我点击提交时,我想要POST以创建以下内容。只有当我点击提交时,我得到一个对象引用错误,引用我输入的值为id = debugTxt。我怀疑因为我丢失了对象状态,我得到了这个错误。

所以我的问题是如何使用来自模型的初始视图设置文本并允许用户在POST上更新?

@using (Html.BeginForm("Create", "PhysDoc"))
{
    <table>
        <tr>
           <td class="title">Debug Mode</td>
           <td>
                This input does the initial GET correctly.  On POST I get object ref error related to the value inside @Model.
                <input type="text" id="debugTxt" name="debugModeTxt" value="@Model.DebugMode" />
            </td>  
        </tr>
        <tr>
            <td>
                <input type="submit" value="Submit" />
            </td>
        </tr>
    </table>                
}

创建方法(注意这里不抛出异常)。

    [HttpPost]
    public ActionResult Create(string debugModeTxt)
    {
        PhysdocSettings settings = new PhysdocSettings();
        settings.DebugMode = bool.Parse(debugModeTxt);
        PhysDocSettingsBL settingBL = new PhysDocSettingsBL();
        settingBL.UpdateSettings(settings);
        return View("Index");
    } 

此处发生异常:

value="@Model.DebugMode"如果我更改value="True",我的代码就可以了。但这并没有给我一个等于Model.DebugMode的初始值。

1 个答案:

答案 0 :(得分:3)

尝试此操作...使用HTML帮助程序并为字段指定默认值,如下所示:

@Html.TextBox("[name]", @Model.DebugMode)

如果这不起作用你能详细说明结果吗?


当您致电return View("Index");时,您没有将模型传递给索引。你只是在调用视图,因此你确实会得到一个Null Reference Exception。