Tuesday 16 May 2017

Return XML file from Controller's Action method to View in MVC

Return XML file from Controller's Action method to View in ASP.Net MVC

Description:
In this example wee explain that how to returning the XML file from Controller to View in asp.Net MVC.or how to return XML file from Controller’s Action Methods to View in MVC Razor.


Suppose you have one Employee XML file and then you want to display this file in Razor View then you can easily read or return the XML file from Action Method of Controller to View in Razor MVC.

Main point is that to return the XML file ContentResult return type is used for returning the xml file from controller to View in asp.net MVC.
XMLFile:

<?xml version="1.0" standalone="yes"?>
<Employees>
 <Employee>
    <Id>1</Id>
    <Name>Kirit Patel</Name>
    <Country>United States</Country>
 </Employee>
 <Employee>
    <Id>2</Id>
    <Name>Umesh rathod</Name>
    <Country>India</Country>
 </Employee>
 <Employee>
    <Id>3</Id>
    <Name>Sazid khan</Name>
    <Country>France</Country>
 </Employee>
 <Employee>
    <Id>4</Id>
    <Name>John vaas</Name>
    <Country>UK</Country>
 </Employee>
</Employees>

Controller: 
public class EmployeeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ContentResult AjaxMethod()
    {
        string xml = System.IO.File.ReadAllText(Server.MapPath("~/XML/Employees.xml"));
        return Content(xml);
    }
}

View:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <input type="button" id="btnGet" value="Get XML"/>
    <hr/>
    <textarea id="txtXml" rows="25" cols="40" style="border:none; overflow:hidden"></textarea>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnGet").click(function () {
                $.ajax({
                    type: "POST",
                    url: "/Employee/AjaxMethod",
                    data: '',
                    contentType: "application/json; charset=utf-8",
                    dataType: "text",
                    success: function (response) {
                        $("#txtXml").val(response);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html>


This entry was posted in :

0 comments:

Post a Comment