Return a string from MVC Controller to jQuery

asp.net, asp.net-mvc, asp.net-mvc-4, c#, jquery

Solution

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>

Problem

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] ```

Original source