Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a string from MVC Controller to jQuery [closed]

I want to make a call to an ASP.NET MVC4 Controller and have it return a string to a jQuery method, then output that string with an alert(). The code below only outputs object Object.

jQuery:

$launchTRs = function (appID) {
    var html = $.get("/PartialView/GetTRAsString?appID=" + appID, function (data) { });
    alert(html.toString());
}

ASP:

public string GetTRAsString(string appID)
{
    // Populate revisions
    string html = "<ul>";

    foreach(RevesionInfo revInfo in revisions)
    {
        html += "<li>" + revInfo.RevDesc + "</li>";
    }

    html += "</ul>";

    return html;
}

Outut:

[object Object]
like image 862
John 'Mark' Smith Avatar asked Jan 31 '14 10:01

John 'Mark' Smith


2 Answers

In ASP.NET MVC controller actions do not return strings. They return ActionResults.

So start by fixing your action (read below to understand why I put fixing in italic, it's because that's only the first stage):

public ActionResult GetTRAsString(string appID)
{
    // Populate revisions
    string html = "<ul>";

    foreach(RevesionInfo revInfo in revisions)
    {
        html += "<li>" + revInfo.RevDesc + "</li>";
    }

    html += "</ul>";

    return Content(html, "text/html");
}

Also the first A letter in AJAX stands for Asynchronous, so you should put the alert inside your success callback, which is the only place where the result will be available:

$.get('/PartialView/GetTRAsString', { appID: appID }, function (data) { 
    alert(data);
});

Also bear in mind that generating HTML in a controller action is a terrible idea. Mixing C# and HTML leads to ugliness that I prefer not to comment.

In ASP.NET MVC, the V stands for View, so go ahead, use them. The purpose of a controller action is to fetch a model and pass this model to the view in order to project it:

public ActionResult GetTRAsString(string appID)
{
    IEnumerable<Revision> revisions = ... go get your revisions from the DB or something
    return PartialView(revisions);
}

and then your view will be strongly typed to the model and you will generate the necessary markup inside:

@model IEnumerable<Revision>
<ul>
    @foreach (var revInfo in Model)
    {
        <li>
            @revInfo.RevDesc
        </li>
    }
</ul>
like image 168
Darin Dimitrov Avatar answered Nov 15 '22 09:11

Darin Dimitrov


Try this:

var html = "";
$.ajax({
    url: "/PartialView/GetTRAsString",
    method: 'GET',
    data: {appId: appID },
    success: (resp){
        html = resp.html;
    }
});

Then your action method will be:

public JsonResult GetTRAsString(string appID)
{
    // Populate revisions
    string html = "<ul>";

    foreach(RevesionInfo revInfo in revisions)
    {
        html += "<li>" + revInfo.RevDesc + "</li>";
    }

    html += "</ul>";

    return Json(new {html});
}
like image 40
James Avatar answered Nov 15 '22 07:11

James