0

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?

1
  • GetTabData() should accept one more argument to allow for callback function. Commented Dec 26, 2012 at 14:53

1 Answer 1

2

Well, then have your controller action return a PartialView containing the ready-to-be-used HTML fragment instead of a JsonResult:

public ActionResult GetData()
{
    MyViewModel model = ...
    return PartialView(model);
}

Now all you need to do inside your success callback is use the jQuery's .html() function:

success: function (data) {
    $('#someContainingDiv').html(data);
}

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:

@model MyViewModel
<div class="list-products clearfix">
@Html.ActionLink("click me", "MyData", "Home", new { id = Mode.Id }, null)
...

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/MyData which 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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.