Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

asp.net mvc - Updating value provider prior to TryUpdateModel

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 : )

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
    }

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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)

This is described in detail at: http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...