9

I'd like some guidance in returning an XML doc from a controller to a view. In my view, I'd like to traverse the XML doc using JQuery. There are plenty of online examples using JQuery for this use.

I have a PortfolioList() Controller below, which right now just returns the view, but I would like to figure out how to RETURN THE XML RESPONSE. You'll noticed below that I'm writing the XML response to a local file just for testing purposes...

Do I need to cleanly create a model for this ?

    public ActionResult PortfolioList()
    {
        XmlDocument xmlResponse = new XmlDocument();
        XmlDocument xmlRequest = new XmlDocument();

        bool rzInitialized = nitializeRz();
        if (rzInitialized == false)
        {
            ViewBag.Message = "Rz Init has failed. Check if Rz is running";
            return View();
        }
        bool rzConnected = ConnectToRz();    

        ViewBag.Message = "Here you may view a list of portfolios and exposures.";

        // Build Portfolio Select request here !
        RequestBuilder rzRequest = new RequestBuilder();

        // REQUEST FOR PORTFOLIOS !
        string portfoliosRequest = rzRequest.PortfoliosRequest("Portfolios");
        string **portfoliosResponse** = RzClient.sendRequest(portfoliosRequest, false);

        // DEBUG REQUESTS !!
        if (Debugflag)
        {
            rzRequest.DebugOutput("portfolios", portfoliosRequest, portfoliosResponse);
        }
        DisconnectFromRz();

        return View("PortfolioList");
    }
1
  • Yes, you should be creating models for all your views that contain any dynamic data. It's always cleaner that way. Commented Jun 22, 2012 at 15:22

4 Answers 4

10

You can do it as follows.

public ActionResult PortfolioList()
{
    //Your code
    ....
    return this.Content(yourXml, "text/xml");
}
Sign up to request clarification or add additional context in comments.

7 Comments

If you do this, what does the view look like?
Design time view is empty but runtime response will be yourXml
That won't work for OP's usecase - "In my view, I'd like to traverse the XML doc using JQuery."
In that case, this could be a different Action which is being called by his original view using jQuery. What he is looking for is RETURN THE XML RESPONSE. Should be able to manipulate as required.
My view doesn't have much yet except for a <script> tag to load JQuery libraries and ViewBag.Title message. And yes, runtime response will be my XML Response.
|
1

If returning xml document from controller action is all you about a better idea is creating a custom action result.

public class XmlDocumentResult: ContentResult
{
    public XmlDocument XmlDocument { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        if (XmlDocument == null)
        return;

        Content = XmlDocument.InnerXml;
        ContentType = "text/xml";
        base.ExecuteResult(context);
    }
}

Now you can return xml from an action as,

public XmlDocumentResult GetXml()
{
    var xmlDoc = new XmlDocument();
    ...

    return new XmlDocumentResult { XmlDocument = xmlDoc };
}

2 Comments

Mark, That looks very interesting indeed. I've seen this idea posted in a similar xml-related post, but they were discussing the MVCContrib on Codeplex (XmlResult action). In any case the post also contained an override to the ExecuteResult() method. Thank you, as I will experiment with this pronto !!! :-) - Bob
InnerXml will not have the entire document. This is incorrect.
0

Based on another developer's advice, I'm going the Json data format route. It turns out that returning an XML doc from an asp.net Controller back to a View is a COMPLETE nightmare (i.e. I can return the XML doc itself to the browser, but I cannot figure out how to use jQuery to process the xml nodes).

I've gone the route of deserializing the XML doc on the server side, and returning a JsonResult to my View (i.e. using JQuery's Ajax routine to call into my controller).

sample XML serialization code: http://msdn.microsoft.com/en-us/library/58a18dwa.aspx#Y0

Comments

0

I found a jQuery code sample online which works for me ! The code sample parses an xml document as follows (the url is http://www.switchonthecode.com/tutorials/xml-parsing-with-jquery ):

<script type="text/javascript">

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "/Xml/xml_test1.xml",
        dataType: "xml",
        success: parseXml,
        error: function (error) {
            alert("Some problem.");
        }
    });
});

function parseXml(xml) {
    //find every Tutorial and print the author
    $(xml).find("Tutorial").each(function () {
        $("#output").append($(this).find("Title").text() + "<br/>");
        $(this).find("Category").each(function () {
            $("#output").append($(this).text() + "<br />");
        });
        $("#output").append("<br/>");


    });
}

However, I do not understand something like this does NOT work (but rather just dumps the entire innerText of every single element onto my page)...sorry about the commented lines:

//$.ajax({
//    url: "/Portfolios/getPortfolios",
//    type: "POST",
//    dataType: "XML",
//    async: true,
//    success: function (data) {
//        if (!data)
//            alert("No xml data returned.");
//        else {
//            var $xml = $(data);
//            $xml.find("portfolioSummary").each(function () {
//                $('.XmlResp').text("DUDE!");         // text($(this).text());
//            });
//            //alert($xml.text());

//            $('.XmlResp').text("Wow are we getting somewhere ?!!!");
//            $('.XmlResp').replaceWith($xml.text());

//        }
//    },
//    error: function (error) {
//        alert("failed");
//    }
//});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.