【问题标题】:ASP.NET MVC form processing problemASP.NET MVC 表单处理问题
【发布时间】:2009-09-02 21:27:56
【问题描述】:

我的控制器中有以下操作:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, FormCollection formCollection)
    {
        // do stuff with form collection
    }

这很好用。我的问题是,当我使用视图模型对象(比如 MyFormViewModel)时,没有属性包含任何表单详细信息。例如有一个名为 MyName 的属性

在我的表单中,我有一个带有 name="MyName" 的文本输入字段

上面的 formCollection 对象包含一个具有正确值的 MyName 条目

但如果我将上面的代码更改为:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, String MyName)
    {

    }

那么我的名字是空的。

有人知道为什么会这样吗?

编辑:aspx 文件是:

<form action="/mycontroller/edit" method="post" id="myControllerForm" enctype="multipart/form-data">
<fieldset>
<div class="forms">
    <div class="row">
        <label> Name: </label>
        <span class="input_wrapper">
            <%= Html.TextBox("MyName", Model.MyName, new { @class = "text" }) %>
         </span>
    </div>
    <div class="row">
       <input name="" type="submit" />
    </div>
</div>
</fieldset>
</form>

【问题讨论】:

  • 您能否发布您的 FormCollection 类的代码并发布您的 aspx 文件。 sting 值为 null 似乎有点奇怪。
  • 在上面添加了 aspx 文件 - 为格式化道歉
  • 根据您发布的代码,这确实有效...您能解决问题吗?

标签: asp.net-mvc


【解决方案1】:

您在使用 POST 数据更新模型时遇到问题吗? 如果是这样,并且您在表单和实际数据模型中的字段名称相同,您可以简单地执行以下操作:

// POST: /Room/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
    // load the actual data model from the DB using whatever ORM you use...
    MyDataModel model = dataRepository.GetItem(m => m.id == id);

    try
    {
        UpdateModel(model);
        return View(new MyViewModel(model));
    }
    catch
    {
        // error handling...
        return View();
    }
}

UpdateModel(T o);方法调用将使用来自 Controller 的当前 ValueProvider 的数据更新提供的对象。

【讨论】:

  • 不幸的是,这也不起作用。即使在调用 UpdateModel(model) 之后,模型的属性仍然为空
猜你喜欢
  • 2016-12-27
  • 1970-01-01
  • 2014-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
相关资源
最近更新 更多