I've looked around on SO, I can't find a sufficient answer to my question.
I have a wrapper class called Title
defined like this
public class Title
{
private readonly string _title;
public Title (string title) {
_title = title;
}
public static implicit operator Title(string title)
{
return new Title(title);
}
}
I am using this class in an ASP MVC project. Right now I defined a controller like this:
public ActionResult Add(string title)
{
//stuff
}
and this works fine.
However, I wish to automatically bind the posted string value to the Title
constructor, thus accepting a Title
instead of a string
as a parameter:
public ActionResult Add(Title title)
{
//stuff
}
This however, does not work, as I will get the error:
The parameters dictionary contains a null entry for parameter, meaning the model binder can't bind the string to the Title
parameter.
The HTML responsible for posting the title data:
<form method="post" action="/Page/Add" id="add-page-form">
<div class="form-group">
<label for="page-title">Page title</label>
<input type="text" name="title" id="page-title">
</div>
</form>
My question exists of two parts:
1. Why is it not possible to do this, I would expect the bodel binder to use the defined implicit operator to create a Title
instance.
2. Is there a way to still accomplish getting the desired behavior, without explicitly creating a modelbinder?