更新值提供商之前TryUpdateModel

更新值提供商之前TryUpdateModel

本文介绍了更新值提供商之前TryUpdateModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个叫做PetsName属性的类。如果是空白的屏幕上我想因此,如果用户没有输入一个小名,我们强迫'无名',以更新的价值提供者。这不是实际情况..这当然是一个样的,所以像网页上,只等设置默认值的答案将不适合这样的场景:)

Lets say we have a class with a property called PetsName. If it is left blank on the screen I want to update the value provider so if the user doesn't enter a pet name, we force 'unnamed'. This isn't the actual scenario.. this is of course a sample, so answers like 'just set default values on a webpage, etc' won't fit this scenario : )

主要的问题是,我们希望在更新它会使用该模型无论你已经覆盖到更新值左右。我想一个想法是要删除值和添加。当我检查的ModelState,它确实有更新的价值,但是当我打电话TryUpdateModel,值不会被更新。它可能什么IM下面做的是确实是正确的并且这里还有另外一个问题,但我想我会尝试这第一次。谢谢!

The main issue is we want to update the values so when you update the model it will use whatever you have overridden. I guess one idea is to remove the value and add it. When I check ModelState, it does have the updated value, however when I call TryUpdateModel, the value is not updated. Its possible what Im doing below is indeed correct and there is another issue here but I figured I'd try this first. Thanks!

    //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
    }

推荐答案

幕后真正的问题在这里的是,Html.HiddenFor没有显示即使TryUpdateModel在模型更新的价值给予了正确的值视图。

The real issue behind the scenes here is that Html.HiddenFor wasn't displaying the correct value even though TryUpdateModel was updating a value in the model to give to the view.

这里的问题是,HTML辅助假设,如果您呈现一个帖子后认为,有mustve是一个错误(否则你wouldve重定向回用GET方法的观点 - 因此后重定向获取问题)

The issue here is that the Html helpers assume if you are rendering a view after a post, there mustve been an error (otherwise you wouldve redirected back to the view with a GET method - hence the Post Redirect Get issue)

这是在细节,请
http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx

这篇关于更新值提供商之前TryUpdateModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 20:37