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.

有帮助吗?

解决方案

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

其他提示

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.

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.

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".

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top