qinking126
qinking126

Reputation: 11885

asp.net mvc3, how to get the value returned by JsonResult

here's my action.

    public virtual JsonResult AddSearch()
    {
        var data = new { Id = food.Id, Image = food.Image, Name = food.Name};

        return Json(data, JsonRequestBehavior.AllowGet);
    }

here's my aJax form

    @using (Ajax.BeginForm("AddSearch", "Home", new AjaxOptions { OnSuccess = "AddSearch" }))

my javascript file.

    function AddSearch() {
        alert("sdfsdfsdf");
    }

it works, I see the alert box. my question is how I can get the "Id", "Name" and "Image" returned by JsonResult. I tried

        alert("sdfsdfsdf");

it's not working.

Upvotes: 1

Views: 1801

Answers (4)

Shivkumar
Shivkumar

Reputation: 1903

There is one more property in AjaxOption "UpdateTargetId" where your response will append. your View like

<div id="tagetId">
</div>

     @using (Ajax.BeginForm("AddSearch", "Home", new AjaxOptions { OnSuccess = "AddSearch", UpdateTargetId = "tagetId" }))
     {

     } 

In your Controller

public Actionresult  AddSearch()
{
    var data = new { Id = food.Id, Image = food.Image, Name = food.Name};

    return data;
}

you result will be Append in "targertId".

Upvotes: 0

nemesv
nemesv

Reputation: 139758

MVC (to be precise unobtrusiveAjax helpers) will pass the standard jQuery.ajax success(data, textStatus, jqXHR)callback arguments to the OnSuccess method.

So you just need to add the parameters to your AddSearch method:

function AddSearch(data, status, xhr) {
        // you can access your properties from data
        alert(data.Name);
}

Upvotes: 1

lopezbertoni
lopezbertoni

Reputation: 3641

You can try something like this:

In the controller:

public virtual JsonResult AddSearch()
{
    var data = new { Id = food.Id, Image = food.Image, Name = food.Name};

    return Json(data, JsonRequestBehavior.AllowGet);
}

In the view/javascript section:

function AddSearch() {

    $.getJSON("@url.Action(here_goes_your_actionname)", { parameters }, function (data) {

        alert(data);

    });
}

Hope this helps.

Upvotes: 0

Jap Evans
Jap Evans

Reputation: 1127

This is how i did... I accessed the list in my model and converted it to a JSON in my javascript.

var JsonServerList = <%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(@Model.ServerList) %>;

Now when i say ServerList[i].servername i get the values.

Upvotes: 0

Related Questions