您可以编写自定义模型绑定器。让我们举个例子。假设您有以下控制器:
public class HomeController : Controller
{
// Serve the view initially
public ActionResult Index()
{
return View();
}
// This will be called using AJAX and return an XML document to the
// client that will be manipulated using javascript
public ActionResult GetXml()
{
return Content("<foo><bar id=\"1\">the bar</bar></foo>", "text/xml");
}
// This will be called using AJAX and passed the new XML to persist
[HttpPost]
public ActionResult Save(XDocument xml)
{
// TODO: save the XML or something
return Json(new { success = true });
}
}
在客户端上,我们可以有以下 javascript:
<script type="text/javascript">
// send an AJAX request to retrieve the XML initially
$.ajax({
url: '@Url.Action("getxml")',
type: 'GET',
cache: false,
success: function (data) {
// The data variable will contain the initial xml
// Now let's manipulate it:
$(data).find('bar').attr('id', '7');
var xmlString = data.xml ? data.xml : (new XMLSerializer()).serializeToString(data);
// Let's send the modified XML back to the server using AJAX:
$.ajax({
url: '@Url.Action("save")',
type: 'POST',
contentType: 'text/xml',
data: xmlString,
success: function (result) {
// ...
}
});
}
});
</script>
最后一部分是为 XDocument 类型编写自定义模型绑定器,以便 Save 控制器操作可以获取 XDocument:
public class XDocumentModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var request = controllerContext.HttpContext.Request;
if (!request.ContentType.StartsWith("text/xml", StringComparison.OrdinalIgnoreCase))
{
return null;
}
return XDocument.Load(request.InputStream);
}
}
将在 Application_Start 中注册并与 XDocument 类型相关联:
ModelBinders.Binders.Add(typeof(XDocument), new XDocumentModelBinder());