Asp.net MVC ModelState.Clear

Posted by Mr Grok on Stack Overflow See other posts from Stack Overflow or by Mr Grok
Published on 2009-11-21T11:04:10Z Indexed on 2010/03/19 0:41 UTC
Read the original article Hit count: 1440

Filed under:
|

Can anyone give me a succinct definition of the role of ModelState in Asp.net MVC (or a link to one). In particular I need to know in what situations it is necessary or desirable to call ModelState.Clear().

Can anyone give me a succinct definition of the role of ModelState in Asp.net MVC (or a link to one). In particular I need to know in what situations it is necessary or desirable to call ModelState.Clear().

Bit open ended huh... sorry, I think it might help if tell you what I'm acutally doing:

I have an Action of Edit on a Controller called "Page". When I first see the form to change the Page's details everything loads up fine (binding to a "MyCmsPage" object). Then I click a button that generates a value for one of the MyCmsPage object's fields (MyCmsPage.SeoTitle). It generates fine and updates the object and I then return the action result with the newly modified page object and expect the relevant textbox (rendered using <%= Html.TextBox("seoTitle", page.SeoTitle)%>) to be updated ... but alas it displays the value from the old model that was loaded.

I've worked around it by using ModelState.Clear() but I need to know why / how it has worked so I'm not just doing it blindly.

PageController:

[AcceptVerbs("POST")]
    public ActionResult Edit(MyCmsPage page, string submitButton)
    {
        // add the seoTitle to the current page object
        page.GenerateSeoTitle();

        // why must I do this?
        ModelState.Clear();

        // return the modified page object
        return View(page);
    }

Aspx:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyCmsPage>" %>
....
        <div class="c">
            <label for="seoTitle">
                Seo Title</label>
            <%= Html.TextBox("seoTitle", page.SeoTitle)%>
            <input type="submit" value="Generate Seo Title" name="submitButton" />
        </div>

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about modelstate