javascript - Pass the result of AJAX callback to Partial View using JQuery - Stack Overflow

I'm using ASP.NET MVC 4. On a button click, I want to invoke ajax callback to controller method an

I'm using ASP.NET MVC 4. On a button click, I want to invoke ajax callback to controller method and return the data needed as Json Data. I'm able to do this using the following code:

<script>
$(document).ready(function () {
    var ajax_url = '@Url.Action("GetNewItems")';
    $("#submit").click(function () {
        $.ajax({
            url: ajax_url,
            type: "POST",
            datatype: "json",
            success: function (data) {
                debugger
            }
        });
    });
});

[HttpPost]
    public JsonResult GetNewItems()
    {
        List<Item> items = new List<Item>();

        items.Add(new Item() { Id = 3, Name = "c" });
        items.Add(new Item() { Id = 4, Name = "d" });

        return Json(items);
    }

In success function, the collection of Items are returned properly. In this function, I want to call Html.Partial and pass the result as the model of the Partial view. Is this possible?

I've searched in other threads, but most of them are suggesting that Partial View is returned from Controller method and html(data) is used to render it. I'd rather not return the Partial view from Controller, as the size would have significant difference rather than returning the data only and render it manually in client-side.

So, is it possible to pass the result to Partial view in success function, or I have to manually render the elements in there?

Any help is appreciated. Thanks!

I'm using ASP.NET MVC 4. On a button click, I want to invoke ajax callback to controller method and return the data needed as Json Data. I'm able to do this using the following code:

<script>
$(document).ready(function () {
    var ajax_url = '@Url.Action("GetNewItems")';
    $("#submit").click(function () {
        $.ajax({
            url: ajax_url,
            type: "POST",
            datatype: "json",
            success: function (data) {
                debugger
            }
        });
    });
});

[HttpPost]
    public JsonResult GetNewItems()
    {
        List<Item> items = new List<Item>();

        items.Add(new Item() { Id = 3, Name = "c" });
        items.Add(new Item() { Id = 4, Name = "d" });

        return Json(items);
    }

In success function, the collection of Items are returned properly. In this function, I want to call Html.Partial and pass the result as the model of the Partial view. Is this possible?

I've searched in other threads, but most of them are suggesting that Partial View is returned from Controller method and html(data) is used to render it. I'd rather not return the Partial view from Controller, as the size would have significant difference rather than returning the data only and render it manually in client-side.

So, is it possible to pass the result to Partial view in success function, or I have to manually render the elements in there?

Any help is appreciated. Thanks!

Share Improve this question edited Feb 17, 2014 at 10:12 Tasos K. 8,0977 gold badges42 silver badges65 bronze badges asked Feb 17, 2014 at 9:54 erikaerika 1242 silver badges7 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

so what's the problem? just do it

    [HttpPost]
    public ActionResult GetNewItems()
    {
        List<Item> items = new List<Item>();

        items.Add(new Item() { Id = 3, Name = "c" });
        items.Add(new Item() { Id = 4, Name = "d" });

        return View("MypartialView",items);
    }

$(document).ready(function () {
    var ajax_url = '@Url.Action("GetNewItems")';
    $("#submit").click(function () {
        $.ajax({
            url: ajax_url,
            type: "POST",
            success: function (data) {
                $("#div").html(data);
            }
        });
    });
});

So, is it possible to pass the result to Partial view in success function, or I have to manually render the elements in there?

you can solve this problem in couple of way -

  • use AJAXFORM Post.
  • Alternatively you can use JQuery templates.

JQuery Templates solution

First reference following JQuery libraries -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="http://ajax.microsoft./ajax/jquery.templates/beta1/jquery.tmpl.js" type="text/javascript"></script>

Then create the template which you want to fill up with details -

<script id="personsTmpl" type="text/x-jquery-tmpl">
    <tr>
        <th>${Name}</th>
    </tr>
</script>

As a next step define the Table in html -

<table id="tableAttendees">
    <thead>
        <tr>
            <th>Name</th>
        </tr>
    </thead>
    <tr></tr>
</table>

Have a button on the page -

<input type="button" value="Click" onclick="submitForm()" />

Finally handle the JQuery Click event of the Submit button -

<script>
    function submitForm() {
        jQuery.ajax({
            type: "POST",
            url: "@Url.Action("Submit")",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ name: "Rami" }),
            success: function (data) {
                $("#personsTmpl").tmpl(data).appendTo("#tableAttendees");
            },
            failure: function (errMsg) {
                alert(errMsg);
            }
        });
    }
</script>

When the button is clicked, Submit Action will be hit -

    public ActionResult Submit(string name)
    {
        return Json(new Person() { Name = name + " Its Me" });
    }

which would return person object -

public class Person
{
    public string Name { get; set; }
}

Now when you run the application, and click on the button, you will see the values getting appending to the table as below -

Alternatively you can use AJAX form as shown below.

AJAXFORM Solution

Say you have Index as below -

@model MVC.Controllers.Person
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

@using (Ajax.BeginForm("Submit", new AjaxOptions { UpdateTargetId = "productList" }))
{
    <div>
        @Html.LabelFor(model => model.Name)
        @Html.EditorFor(model => model.Name)
    </div>
    <div>
        <input type="submit" value="Add Product" />
    </div>
}

<div id='productList'>
    @{ Html.RenderPartial("itsme", Model); }
</div>

Which will hit Submit action and in turn we get a partial view -

    public ActionResult Submit(Person p)
    {
        p.Name = p.Name + " Its me";
        return PartialView("itsme", p);
    }

And the partial view is simple which display the name -

@model MVC.Controllers.Person

@if (Model != null)
{
    @Html.LabelFor(p => p.Name, Model.Name)
}

Finally the output -

If you don't want to return Partial View then you have to use a client side code to acplish this. There are several options. You could review jTempaltes and jQuery Templates as an options. But if you won't call more than once this Ajax I would remend you to return Partial View.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745404161a4626238.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信