Return a string from MVC Controller to jQuery

53,572

Solution 1

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>

Solution 2

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});
}

Solution 3

One more solution using AJAX -

Controller Action -

    public ActionResult GetString(string input)
    {
        return Content(input + ", Hello!!!");
    }

View -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(function () {
        $('#click1').click(function (e) {
            $.ajax({
                url: "@Url.Action("GetString")",
                type: "GET",
                dataType: "json",
                data: {
                    input: 'John'
                },
                error: function (response) {
                    alert(response.responseText);
                },
                success: function (response) {
                    alert(response);
                }
            });
        });
    });
</script>
<input type="button" value="Click Me" id="click1" />

And when you click -

enter image description here

Solution 4

Will suggest to return JSONResult, as it's most common practice for such cases + use templating engine, like Mustache, or what ever else, rather then just fill handmade template within values on server side.

like this:

server stuff:

public JSONResult ActionName()
{
   var result=new { Success="False", Message="Error Message"};
   return Json(result, JsonRequestBehavior.AllowGet);
}

client stuff:

var template = "<h1>{{your property values here}}</h1>", 
    html = '';

$('#sampleArea').html(html);
    $.getJSON('YourController/ActionName', function(data) {
         html = Mustache.to_html(template, data);
    });

more information above:

  1. http://coenraets.org/blog/2011/12/tutorial-html-templates-with-mustache-js/
  2. http://shashankshetty.wordpress.com/2009/03/04/using-jsonresult-with-jquery-in-aspnet-mvc/
Share:
53,572
John 'Mark' Smith
Author by

John 'Mark' Smith

I have come to ask questions.

Updated on July 16, 2022

Comments

  • John 'Mark' Smith
    John 'Mark' Smith almost 2 years

    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]
    
  • MDave
    MDave almost 9 years
    The alert always comes from the error, because it's expecting json. Remove the line: dataType: "json", and in the controller instead return Content(input + ", Hello!!!", "text/html"); and the alert will come from the success.
  • Rajshekar Reddy
    Rajshekar Reddy over 6 years
    I have a question on your comment Mixing C# and HTML leads to ugliness that I prefer not to comment. doesn't the inbuilt HTML helpers do the same?