asp.net-mvcasp.net-mvc-4model-view-controllermodelbinder

Remove prefix from posted data in asp.net mvc


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();
        }

Solution

  • Try adding a binding prefix value, like this:

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