I’m sending user request from mvc view to the controller and controller after some processing send result as json object back to the view.
my current solution working but I want to render html elements on the view side, not in the js function (as it is now).
function GetTabData(xdata) {
$.ajax({
url: ('/Home/GetData'),
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id: xdata }),
success: function (result) {
var data = null;
data = '<div class="list-products clearfix">
data += '<a href="/Home/MyData/' + item.Id + '">
....
}
so I want to remove all this divs and other html elements and send pure data and format this on the view, how can I do this?
Well, then have your controller action return a
PartialViewcontaining the ready-to-be-used HTML fragment instead of a JsonResult:Now all you need to do inside your success callback is use the jQuery’s
.html()function:you would then have a corresponding partial view (
~/Views/Home/GetData.cshtml) that will be strongly typed to the view model and render the corresponding HTML:As you can see this allows you to use HTML helpers that would generate proper markup and urls, whereas in your original example you were hardcoding urls in your anchor tag like
/Home/MyDatawhich is really a very bad thing to do.You should really find the balance between pure JSON data being sent from your contorller actions invoked by an AJAX requests and sending partial views containing markup. If you find yourself using lots of string concatenations in your AJAX success callbacks in order to build some HTML markup, then you should probably switch your server side logic to directly return the desired HTML.