Tuesday, October 25, 2011

MVC3 ModelState and overwriting model properties

I will expand this later, I swear.

Caution: when you are using strongly typed models in MVC3 and you modify a property of the model in an Action, that property will get discarded when you create the view unless you clear the ModelState first. When building the view, the model fields are overwritten with values from ModelState, so clearing the ModelState prevents this.

UPDATE 11/10/2011:
This only applies to values passed in via a POST (or a GET?) that you're attempting to override by changing the corresponding fields in the view model.

Thursday, October 13, 2011

RegExes for replacing MVC3 hard-coded hrefs with @Url.Content hrefs

I'm posting this here mainly as a memory aid for myself.

My app is sprinkled with lots of links like this:
    <script src="../../Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>

I'd like them to look like this, since NuGet seems to be cognizant of such references and apparently changes them on upgrades:
    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>

So the following search and replace with RegExes will work:

Find what:"\.\./\.\.{/[^"]*}"
Replace with:"@Url.Content("~\1")"

Include the quotes, and be sure to select "Use regular expressions."

Note that the consistent relative path "../../" must be changed as per your circumstances.

UPDATE on 11/2/11:
This "Replace With" parameter might be better:

UPDATE on 11/22/11:
Now, according to this article, I see that Url.Content is supposed to be better anyway.