【问题标题】:Interesting Asp .net mvc example有趣的 Asp .net mvc 示例
【发布时间】:2012-07-24 20:39:45
【问题描述】:

我正在尝试下面解释的基本 asp .net mvc 项目配置;

在第一次提交之前,结果在照片中是预期的,在提交文本框(@Html.TextBoxFor(model => model.Name))和文本(@Model.Name)后显示不同的值,如照片中的右侧所示,出乎意料;为什么会这样?尽管它们的模型是独一无二的,但它们显示出不同的值。

型号:

 public class Personnel
{
    public string Name { get; set; }
}

查看:

@model deneme.Models.Personnel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>


@using (Html.BeginForm("Index", "Home"))
{
    @Html.TextBoxFor(model => model.Name)

    <br/>
    <br/>

    @Model.Name

    <br/>
    <br/>

    <input type="submit" value="submit" />
}

控制器:

public ActionResult Index(Personnel personnel)
{
     if (string.IsNullOrEmpty(personnel.Name))
     {
         personnel.Name = "Ahmet";
     }
     else
     {
         personnel.Name = personnel.Name + "server";
     }

     return View(personnel);
}

【问题讨论】:

  • 您第一次提交表单时是否未填写文本框。然后它根据您的代码工作正常
  • 不,会出现同样的结果。它们仍然不同。
  • 你用的是什么浏览器?我推测浏览器可能会自动填充表单域......
  • 我在多个浏览器中尝试过,@Vedran 解决了这个问题。 ModelState.Clear() 解决。

标签: asp.net-mvc


【解决方案1】:

编辑:我之前的回答没有回答你的问题。

如果您将ModelState.Clear() 添加到控制器操作中,它将按您的意愿工作。

public ActionResult Index(Personnel personnel)
{
     if (string.IsNullOrEmpty(personnel.Name))
     {
         personnel.Name = "Ahmet";
     }
     else
     {
         personnel.Name = personnel.Name + "server";
     }

     ModelState.Clear();
     return View(personnel);
}

【讨论】:

  • 真正的问题是为什么 text 和 textbox 在提交后有不同的值?两者都与同一个模型有关。
  • @serefbilge,我误解了这个问题,这应该可以解决它。
  • 是的,它起作用了,机制是什么?有没有类似视图状态的东西(我认为是模型状态)?
  • 看看这个问题的答案:stackoverflow.com/questions/1775170/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-02
  • 1970-01-01
  • 2020-09-17
相关资源
最近更新 更多