简体   繁体   中英

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

Try adding a binding prefix value, like this:

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

    ...
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM