Gareth Lewis
Gareth Lewis

Reputation: 751

Dynamically inserting HTML into View through AJAX

In my view, I would like to insert an HTML table detailing a user's equipment when his/her name is selected from a drop down menu. I'd like to do this without reloading the page, so I'm looking for an AJAX solution. My current solution is working fine, but I think that there must be a better solution out there.

I'm using jQuery like this (just using <p> tags at the moment, and would get very messy if I try to code a HTML table in there):

$.getJSON(url, { networkName: $('#Incident_Caller_DomainUserID option:selected').text() }, function (data) {
    $('#EquipmentList').empty();
    $.each(data, function (index, optionData) {
        $('#EquipmentList').append('<p>' + optionData.Product + '</p>');
    });
});

Which does a POST request to the GetCallerEquipment Action in the AjaxData Controller

public JsonResult GetCallerEquipment(string networkName)
{
    JsonResult result = new JsonResult();
    result.Data = repository.GetCallerEquipment(networkName);
    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

    return result;
}

Could I use a partial view for this? That seems the best way to go about it, but I have no idea where to start, so some advise or links to examples or tutorials would be very much appreciated.

Thanks.

Upvotes: 0

Views: 94

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

Could I use a partial view for this?

Sure:

public ActionResult GetCallerEquipment(string networkName)
{
    var model = repository.GetCallerEquipment(networkName);
    return PartialView(model);
}

and then inside your GetCallerEquipment.cshtml partial:

@model SomeViewModel
<table>
    ...
</table>

and then:

var networkName = $('#Incident_Caller_DomainUserID option:selected').text();
$('#someContainer').load(url, { networkName: networkName });

Upvotes: 1

Andreas Eriksson
Andreas Eriksson

Reputation: 9027

A partial view would be great.

Just make your controller return one, and then do something like this:

$.get('@Url.Action("YourActionName", "YourControllerName")', 
       { anydata: youmaywanttopass },
       function(result) { 
           $("#EquipmentList").html(result);
       }
);

That's it. The "result" returned from the get-request will be your partial view html.

Upvotes: 2

Related Questions