Arman Hayots
Arman Hayots

Reputation: 2508

MVC Razor submit data in XML

That's me again with MVC Razor. In web i see a lot of tutorials by sending data from JQuery to Controller and vice-versa via AJAX using JSON, but I can't find any similar example with XML. Any examples, tutorials, faqs?

Upvotes: 2

Views: 941

Answers (1)

Brad Christie
Brad Christie

Reputation: 101614

JSON is commonly used because it's almost married to MVC (and integrates nicely). But, depending on your setup, you should be able to handle XML nicely (as long as you don't mind it being a string at the transport layer, then use a Javascript or C# library to manage it on either side of the boundary).

To give a complete work-flow, start with the GET action:

public ActionResult MyAction()
{
    MyObjWithXml model = new MyObjWithXml
    {
        // XML could be a serialized object or something form a data source
        xml = "<FOO><BAR>baz</BAR></FOO>";
    };
    return View(model); 
}

Then the view:

@model MyObjWithXml
@using (html.BeginForm("MyAction", "MyController", Httpmethod.Post))
{
    // Model.xml = "<FOO><BAR>baz</BAR></FOO>"
    @Html.HiddenFor(x => x.xml)
    <input type="submit" value="Submit" />
}

Now let's send it back (Likewise you could AJAX is off as well):

 [HttpPost]
 // may also need [AllowHtml]/[ValidateInput(false)] to allow XML characters
 public ActionResult MyAction(MyObjWithXml model)
 {
     if (ModelState.isValid)
     {
       // model.xml = "<FOO><BAR>baz</BAR></FOO>";
       // process and do what you need (maybe deserialize it back to whatever
       // you needed or save it off to a datasource
     }
     return View();
 }

as far as displaying it (in a non-editable capacity) you can either dump it raw to the page (maybe as a text/xml data type) or maybe work with it after parsing it using jQuery ($.parseXML('@Html.Raw(Model.xml)');) -- your call.

Upvotes: 1

Related Questions