该文本区域为零

时间:2011-09-26 03:58:35

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

我有一个奇怪的问题,过去几个小时让我很沮丧。我似乎找不到任何相关的东西;也许我不够具体,因为我不确定如何正确地说出来,或者这是一个奇怪的独特问题。

有一个用户填写的表单来更新他们的帐户信息,一切正常,除了一个文本区域。一旦表单被POST,该文本区域'(绑定到Comments的属性UserInfo)值将变为null。 Comments属性是唯一的null属性。

何时发生
A)没有现有值,用户输入值,属性为空 B)现有值,用户确实/不会改变某些东西/什么,属性为空。

我只会包含相关代码,以保持简洁明了。希望这已经足够了。

控制器操作

public ActionResult Edit_Information(long id)
{
    // Get user info from the database.
    // Return the view with the user info from the DB etc.
}

[HttpPost]
public ActionResult Edit_Information(long id, UserInfo userInfo)
{
    if (!this.ModelState.IsValid)
    {
        // Invalid
        return View(userInfo);
    }

    // Update the information in the DB.

    // Redirect the user back to their account.
}

Razor查看HTML

<div style="width: 700px; margin-left: auto; margin-right: auto; text-align: left">
@Html.ValidationMessageFor(x => x.Comments)
</div>
@Html.Partial("~/Views/Shared/_EditorSmiles.cshtml")
@Html.TextAreaFor(x => x.Comments, new { @class = "EditorArea profile-comments" })

UserInfo 型号

[Validator(typeof(UserInfoValidator))]
public class UserInfo
{
    public string Comments { get;set; }
}

是的,我在模型上使用FluentValidation。我删除它以查看它是否是原因,但事实并非如此。

我尝试过的事情

  • 在POST操作中,我使用FormCollection formCollection代替UserInfo userInfo
  • 在POST操作上抛出异常,以证明该值在发布时变为null。
  • 创建了一个名称不同的新媒体资源。
  • 在返回视图之前手动为属性赋值。发布时,该值变为空。
  • 在POST操作中手动赋予属性一个值,以证明它不是数据库或SQL。这很有用。
  • 从模型中删除了Fluent Validation属性(如上所述)。
  • [Bind(Prefix = "")]之前使用UserInfo userInfo。这并没有改变任何事情。

令我感到沮丧的是,我不得不问:这到底是怎么回事?难道我做错了什么?我必须忽视一些事情。页面上还有另一个文本区域可以正常工作。它只是Comments的文本区域,无论条件如何,它始终返回空值。

1 个答案:

答案 0 :(得分:3)

表格被包裹起来:

Html.BeginWindow();
Html.BeginForm("edit_information", "user", FormMethod.Post, new { id = "profile" });
<!-- other stuff goes in between here -->
Html.EndForm();
Html.EndWindow();

Html.BeginWindow()生成一个包裹在表单周围的表(窗口)。这显然导致表单的某些部分无法正确发布。

更改为:

Html.BeginForm("edit_information", "user", FormMethod.Post, new { id = "profile" });
Html.BeginWindow();
<!-- other stuff goes in between here -->
Html.EndWindow();
Html.EndForm();

的Bam!它再次起作用。这件事从未发生过,因为我之前没有遇到任何问题。我很高兴这是固定的。我们都犯错误。