Sergey
Sergey

Reputation: 8091

Is it possible to bind into Key/Value dictionary inputs in format InputName/InputValue

Is it possible to bind into Key/Value dictionary inputs in format InputName/InputValue?

Upvotes: 0

Views: 134

Answers (2)

VJAI
VJAI

Reputation: 32768

If you want the values in the form come and sit as List<KeyValuePair<string,string>> in action methods you have to for custom model binder.

public class CustomModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var form = controllerContext.HttpContext.Request.Form;  
        return form.Cast<string>().Select(s => new KeyValuePair<string,string>(s, form[s])).ToList();
    }
}

[HttpPost]
public ActionResult Save(List<KeyValuePair<string,string>> form)
{
  ...
}

If you are fine with other options you can go for FormCollection as @Tommy suggested. By the way FormCollection is a built-in dictionary class that contains all the values submitted by the form.

You can also create a simple class having properties with names as the form field names and the default model binder automatically instantiate and set the values for the class and provide to the action. This is the approach people usually follow.

Upvotes: 1

Tommy
Tommy

Reputation: 39807

MVC already does this if you pass the right parameter to your action method. Note - it is highly recommended to use strongly typed views and models in your action methods.

With that said, if your method signature uses the following:

public ActionResult MyMethod(FormsCollection MyFormValues)

Then in your code, you can use

var myFormValue = MyFormValues("InputName");

Where InputName is the key used from the FormsCollection which will give you the value that was set from the HTML.

Upvotes: 0

Related Questions