假设我们有一个名为PetsName的类。如果它在屏幕上留空,我想更新值提供者,所以如果用户没有输入宠物名称,我们强制“未命名”。这不是实际场景..这当然是一个示例,所以像“只是在网页上设置默认值等”的答案将不适合这种情况:)
主要问题是我们想要更新值,因此当您更新模型时,它将使用您覆盖的任何内容。我想一个想法是删除值并添加它。当我检查ModelState时,它确实具有更新的值,但是当我调用TryUpdateModel时,该值不会更新。它可能我在下面做的确实是正确的,这里还有另一个问题,但我想我先试试这个。谢谢!
//Sample case:
[HttpPost]
public ActionResult Edit(PetOwner petOwner)
{
//If pets name is not set, force to "Unknown"
if(petOwner.PetsName=="")
{
//Tried this too ModelState.Remove("PetsName");
//ModelState.Add("PetsName", new ModelState());
ModelState["PetsName"].Value = new ValueProviderResult("Unnamed", "Unnamed", CultureInfo.CurrentCulture);
}
//Get the record/relationships from DB to merge with ModelState
PetOwner petOwnerToSave = from o in ctx.PetOwners where o.PetOwnerId == petOwner.PetOwnerId select o;
TryUpdateModel(petOwnerToSave);
//Save petOwnerToSave
}
//Sample case:
[HttpPost]
public ActionResult Edit(PetOwner petOwner)
{
//If pets name is not set, force to "Unknown"
if(petOwner.PetsName=="")
{
//Tried this too ModelState.Remove("PetsName");
//ModelState.Add("PetsName", new ModelState());
ModelState["PetsName"].Value = new ValueProviderResult("Unnamed", "Unnamed", CultureInfo.CurrentCulture);
}
//Get the record/relationships from DB to merge with ModelState
PetOwner petOwnerToSave = from o in ctx.PetOwners where o.PetOwnerId == petOwner.PetOwnerId select o;
TryUpdateModel(petOwnerToSave);
//Save petOwnerToSave
}
答案 0 :(得分:4)
这背后的真正问题是Html.HiddenFor没有显示正确的值,即使TryUpdateModel正在更新模型中的值以提供给视图。
这里的问题是Html助手假设你在帖子之后渲染一个视图,一定是一个错误(否则你会用GET方法重定向回到视图 - 因此Post Redirect Get问题)