user2320476 user2320476 - 6 months ago 53
Ajax Question

How to return Json data to a partial view

I have an index page that uses a layout page. On the index page I have a dropdown and a div section
for hosting partial views. I am doing it this way because I plan to have about 4 links and the 4 links
will load different partial views.

<div class="selectOption1" id="custNum">
<label for="ddlCustomerNumber">Customer #:</label>
<select id="ddlCustomerNumber" name="ddlCustomerNumber">
<option value="1001">1001</option>
<option value="1002">1002</option>
<option value="1003">1003</option>
<option value="1004">1004</option>
</select>
</div>


<div id="pageContent"></div>


In the script section of the html I am making an Ajax call
that will fetch jason data and then bind the fields retrieved
on the controls that exist in my loaded partial view. This simple means
that in my partial view I have textboxes for customerfirstname,customerlastname and address.

$('#ddlCustomerNumber').change(function () {
$.ajax({
url: '@Url.Action("PopulateTextBoxes", "Home")',
type: "GET",
data: {
"customerNumber": $(this).val(),
"Country": $("#divcountry").text().trim()
},
success: function (data) {
if (data != null) {
for (var x = 0; x < data.length; x++) {
$("#Customerfirstname").val(data[x].customerfirstname);
$("#Customerlastname").val(data[x].Customerlastname);
$("#Address").val(data[x].Address);
}
}
}
});

});


Here is the method that gets me the json data that I plan to bind to controls
in my partial view.

public ActionResult PopulateTextBoxes(Int32 customerId, string country)
{
try
{
var relatedCustomerInfo = GetOtherCustomerInfo(customerId, country, sRadSelection);
return Json(relatedCustomerInfo, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
logger.Error(ex);
return View("Error");
}

}


Question: I know I can return a partialview from my PopulateTextBoxes method but because I am already
returning json this is not possible. How can I return this json data to my partial view.

Answer

Have a look at this link - How to load partial views in MVC using AJAX

Here's another example:

Java script:

$.get( '@Url.Action("PopulateTextBoxes","Home", new { customerId = Model.ID } )', function(data) {
    $('#outputContainer').html(data);
}); 

Controller:

public ActionResult PopulateTextBoxes(Int32 customerId, string country)
{
    try
    {
        var relatedCustomerInfo = GetOtherCustomerInfo(customerId, country, sRadSelection);
        return PartialView("~/Views/Home/_Partial.cshtml",relatedCustomerInfo);
    }
    catch (Exception ex)
    {
        logger.Error(ex);
        return View("Error");
    }
}

Might have to tweak this a little to get it working exactly the way you want to but it seems like you know MVC well enough to come right

Comments