Reputation: 32868
I have an "Edit" action and an "Edit" view to allow users to update a certain entity in the database.
It's database type is "XML", and the DataContext (I'm using Linq-to-SQL) represents it as a property of type "XElement".
In my view, I render a text-area from the "ToString()" output of the propery like this:
<%= Html.TextArea("Text", Model.Text.ToString()) %>
This works fine when pulling the data from the object, but when I try to post the new data back, it comes back as blank.
I think this is because the auto-binder doesn't know how to deal with a property of type XElement.
Is there a way to fix this, or to somehow customize the behavior of the auto-binder so that it de-serializes the incoming data properly?
Upvotes: 1
Views: 1215
Reputation: 32104
You can write a custom binder for this that implements the IModelBinder
interface. You can register this binder on the method itself:
public ActionResult Edit([ModelBinder(typeof(XElementBinder))] XElement element)
{ ... }
or globally for all XElement
's in your application by registereing your binder in Global.asax
:
ModelBinders.Binders[typeof(IPrincipal)] = new PrincipalModelBinder();
Your custom binder would 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;
}
}
Upvotes: 2