我有一个简单的ASP。. NET MVC 3虚拟应用程序(只是从WebForms学习MVC)。
我很困惑如何更新表单,而实际上没有一些DB之间的东西。我只是有一个文本框的形式,我按下按钮后,我想看到大写的字符串。但我什么也没发生。
控制器:
public ActionResult Index()
{
ToUppercaseModel model = new ToUppercaseModel { TheString = "testing" };
return View(model);
}
[HttpPost]
public ActionResult Index(ToUppercaseModel model)
{
model.TheString = model.TheString.ToUpper();
return View(model);
}
模型:
public class ToUppercaseModel
{
[Display(Name = "My String")]
public string TheString { get; set; }
}
And view:
@using (Html.BeginForm()) {
<div>
<div class="editor-label">
@Html.LabelFor(m => m.TheString)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.TheString)
</div>
<p>
<input type="submit" value="Convert" />
</p>
</div>
}
我认为这很简单。很明显,第二指数方法中的return View(model);
不起作用。我看到了一些关于RedirectToAction()
和在TempData
中存储数据的东西。大多数例子只是提交一些id,但由于我没有db,这不起作用。
如果我这样做:
return RedirectToAction("Index", model);
我得到一个
没有为这个对象定义无参数构造函数。
错误消息。这应该很简单,不是吗?我想我理解Post/Redirect/Get的概念,但不知道如何将其应用于这样简单的事情。
谢谢你的解释
当MVC呈现视图时,它将使用字段的尝试值,而不是模型的值,如果它存在(例如,在日期字段中我放了"Tuesday",这不会模型绑定,但你会想向用户显示字段和他们的输入,并突出显示为无效),你改变了模型的值,而不是尝试值。
尝试的值保存在modelstate字典中:
ModelState["KeyToMyValue"].Value.Value.AttemptedValue
访问和更改这些值可能会很棘手,除非您希望在代码中加载魔法字符串,并且由于验证发生在模型绑定上,您更改的值将不会被验证。
在这种情况下,我的建议是调用ModelState.Clear()
,这将删除所有验证和尝试值,然后直接更改您的模型。最后,您希望通过使用TryValidateModel(yourModel)
对模型进行验证。
请注意,此方法可能是最简单的非hack方法,但会从返回的视图中删除无法绑定的尝试值。
你必须从2个方法中调用1个方法,但是你必须改变它
public ActionResult Index(ToUppercaseModel model)
和发送给1方法你的模型。
public ActionResult Index(ToUppercaseModel? model)
{
if (model == null)
ToUppercaseModel model = new ToUppercaseModel { TheString = "testing" };
return View(model);
}
我想我有一个解决方案,它的作品,但不确定这是它应该的方式?
基本上,我只是把我的模型放入TempData并再次调用normal Index方法。
public ActionResult Index()
{
ToUppercaseModel model = null;
if (TempData["FeaturedProduct"] == null)
{
model = new ToUppercaseModel { TheString = "testing" };
}
else
{
model = (ToUppercaseModel)TempData["FeaturedProduct"];
}
return View(model);
}
[HttpPost]
public ActionResult Index(ToUppercaseModel model)
{
model.TheString = model.TheString.ToUpper();
TempData["FeaturedProduct"] = model;
//return View(model);
return RedirectToAction("Index");
}