Auto binding property "XElement" in ASP.NET MVC
I have an action "Edit" and "Change" to allow users to update a specific object in the database.
This database type is "XML", and the DataContext (I'm using Linq-to-SQL) represents it as a property of type "XElement".
In my opinion, I am rendering the text area from the output of ToString () corresponding to this:
<%= Html.TextArea("Text", Model.Text.ToString()) %>
This works great when fetching data from an object, but when I try to send new data back, it returns as empty.
I think this is because the auto lens doesn't know how to handle a property of type XElement.
Is there a way to fix this or tweak the auto-binding behavior in some way so that it serializes the incoming data correctly?
a source to share
You can write a custom binder for this that implements the interface IModelBinder
. You can register this binder by the method itself:
public ActionResult Edit([ModelBinder(typeof(XElementBinder))] XElement element)
{ ... }
or globally for everyone XElement
in your application by registering your binder in Global.asax
:
ModelBinders.Binders[typeof(IPrincipal)] = new PrincipalModelBinder();
Your custom binder will look something like this:
public class XElementModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
string text = controllerContext.HttpContext.Request.Form["Text"];
XElement element = ...;
// Get XElement instance from posted data.
return element;
}
}
a source to share