1

I have a view which looks like below. Each field has a prefix attached in the name property, but the model in my backend has property without the prefix.

@using (Html.BeginForm("Save", "Home", FormMethod.Post))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <input type="hidden" name="prefix" value="prefix"/>
        <input type="text" id="prefix.Name" name="prefix.Name"/>
        <input type="submit" value="submit" />
    </fieldset>
}

My Action Method looks something like below :

public ActionResult Save([ModelBinder(typeof(CustomModelBinder))]Employee employee)
        {
            throw new NotImplementedException();
        }

My Model looks like :

public class Employee
    {
        public string Name { get; set; }
    }

Can someone help me how to achieve this through custom model binder, i want to strip prefix from each of the posted form items name.

Posted form data :

prefix:prefix
prefix.Name:Hello World!!

I tried below code as well but it's not working. Can someone explain whats wrong here.

public ActionResult Save([Bind(Prefix = "prefix")]Employee employee)
        {
            throw new NotImplementedException();
        }
Saurabh Agrawal
  • 639
  • 6
  • 21
  • I think this is exactly what you need: http://www.codeproject.com/Articles/605595/ASP-NET-MVC-Custom-Model-Binder – Icarus Apr 22 '15 at 18:47
  • I have already looked at it. This is an example of custom model binder. My requirement is similar to this but not exactly the same. My form data has prefix value, i want to strip that prefix value before model binding happens so that it can get binded to my model – Saurabh Agrawal Apr 22 '15 at 18:50

3 Answers3

2

Try adding a binding prefix value, like this:

public ActionResult SetPassword([Bind(Prefix = "Form")] UserSetPasswordForm form)
{
    if (!ModelState.IsValid)
    {
        ....
    }

    ...
}
souplex
  • 981
  • 6
  • 16
  • Below code is not working, value of Name property is just prefix now :public ActionResult Save([Bind(Prefix = "prefix")]string Name) { throw new NotImplementedException(); } – Saurabh Agrawal Apr 22 '15 at 19:09
0

You could use BindAttribute for his

public ActionResult Submit([Bind(Prefix = "L")] string[] longPropertyName) {

}

there is a similar question to yours here: Asp.Net MVC 2 - Bind a model's property to a different named value

Community
  • 1
  • 1
Aram
  • 5,537
  • 2
  • 30
  • 41
0

There was some strange behavior, when i changed my prefix value it started working.

public ActionResult Save([Bind(Prefix = "**someothervalue**")]Employee employee)
        {
            throw new NotImplementedException();
        }

Thanks everyone for your help.

Saurabh Agrawal
  • 639
  • 6
  • 21