What am I doing wrong in trying to create a model binder?
I have this model:
public class QuestionSimple
{
public string Body { get; set; }
public bool IsSingleChoice { get; set; }
public List<String> Answers { get; set; }
public string Difficutly { get; set; }
public string Explanation { get; set; }
}
Which I try to bind using this line in the Global.asax.cs
ModelBinders.Binders.Add(typeof(QuestionSimple), new AddQuestionSimpleBinder());
...With this binder
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// Get the raw attempted value from the value provider
string k开发者_StackOverflow中文版ey = bindingContext.ModelName;
ValueProviderResult val = bindingContext.ValueProvider.GetValue(key);
//val is ALWAYS NULL
return null;
}
But val is alsways null.
Here is the View which should return (and actually does return) list of answers, when I'm not using my binder. @using (Html.BeginForm("AddQuestionSimple", "Topic", FormMethod.Post, new { @id = "mainForm" }))
{
<input type="text" name="questionToBeAdded.Answers[0]" value="ff" />
<input type="text" name="questionToBeAdded.Answers[1]" value="ddds" />
<input type="text" name="questionToBeAdded.Answers[2]" value="ff" />
<input type="text" name="questionToBeAdded.Answers[3]" value="ddds" />
<input type="text" name="questionToBeAdded.Answers[4]" value="ff" />
<input type="text" name="questionToBeAdded.Answers[5]" value="ddds" />
<input value="Add question" type="submit" style="position: static; width: 10em; height: 3em;
font-size: 1em;" />
}
The default model-binder does get my values when I post them, but my val
is always null
.
Edit 1:
Here is the supposed to be bound action [HttpPost]
public ActionResult AddQuestionSimple(PMP.WebUI.Models.UserInteractionEntities.UserInput.QuestionSimple questionToBeAdded)
{
return View("AddQuestion");
}
Thanks.
First, you have to override the BindModel, so your method would begin with:
public override object BindModel
Next, you won't find a value with the key "questionToBeAdded" in your bindingContext.ValueProviders
. Debug and look at that collection, bindingContext.ValueProviders[1] has a FormValueProvider that has all the properties of your model in there. The way you're doing it, you might have to iterate through that manually. Another way to do it is just to override the BindProperty method, just type:
protected override void BindProperty
In your model binder class and you'll get the method signature filled in (assuming you're inheriting from DefaultModelBinder). In this method you'll get more detail about each property, the piping is done for you.
精彩评论