Sadegh
Sadegh

Reputation: 4341

ASP.NET MVC: Customization

Which section of ASP.NET MVC should be overrided to be able to change the name of fields (Model Properties) in output to a custom things? Something like below:

<input id="IsActive" name="IsActive" type="checkbox" />

to this:

<input id="MYCUSTOMFORMAT-IsActive" name="MYCUSTOMFORMAT-IsActive" type="checkbox" />

This custom formatting shouldn't break down anything such client-side and server-side validation.

Thanks in advance ;)

More Info

I know that we can do this in Display/Editor Templates but i think this will cause infringement.

Upvotes: 0

Views: 128

Answers (2)

Chao
Chao

Reputation: 3043

A simple workaround for this if you want a constant prefix, but not necessarily the right way to do things, would be to use a viewmodel that contains your properties. in this case:

public class CustomViewModel
{
    public bool IsActive {get;set;}
}

[HttpGet]
public ActionResult MyView()
{
    CustomViewModel MYCUSTOMFORMAT = new CustomViewModel();
    return View(MYCUSTOMFORMAT);
}

[HttpPost]
public ActionResult MyView(CustomViewModel MYCUSTOMFORMAT){
    return View(MYCUSTOMFORMAT);
}

This will give you an Id of MYCUSTOMFORMAT.IsActive.

The proper way to do this would likely be overriding the default model binder and how it handles translating names to properties but I don't know model binders well enough to give you much direction on this.

Upvotes: 1

Adam Tuliper
Adam Tuliper

Reputation: 30152

You can override the name in the HtmlAttributes parameter of the Html.TextBoxFor (etc) helper methods - such as:

@Html.TextBoxFor(o=>o.FirstName, new {id = "customId_originalId"})

However since you are changing this on the client side, the server side will not be able to recognize these changed names and will not bind properly unless you write your own model binder. As such it probably isn't aware of the server side validations to link this to either so again you are stuck handling this in a custom rolled manner.

Upvotes: 2

Related Questions