Fka
Fka

Reputation: 6234

Pass data from controller to view via JSONResult

I'd like to send ViewModel from controller to view in JSON format.

Controller:

public ActionResult Select(int pageLimiter)
{
    var viewModel = new ArticlesViewModel
                            {
                                Articles = this.Service.GetArticles(0, 0, 0),
                                ArticlesTotal = this.Service.CountArticles(0),
                                Pages = new List<string>
                                            {
                                                "1", "2", "3"
                                            }
                            };
    return Json(viewModel, JsonRequestBehavior.AllowGet);
}

View:

<ul class="articleList">
@if (@Model != null)
{
    foreach (var article in @Model.Articles)
    {
        <li>
            <header><a href="/Article/@article.ArticleId">@article.Title</a></header>
            <nav>
                <span>@article.AuthorName</span> | 
                <time>@article.PublishDate.ToString("")</time> | 
                <span><a href="/Articles/@article.CategoryId">@article.CategoryName</a></span> | 
                <span>@article.Comments Comments</span>
            </nav>
            <section>
                @article.Content
            </section>
        </li>
    }
}
</ul>

<script type="text/javascript">
$(document).ready(function () {
    GetArticles(5);

    $("#selectPager").change(function () {
        var selectedItem = "";
        $("#selectPager option:selected").each(function () {
            selectedItem = $(this).text();
        });

        GetArticles(selectedItem);
    });
});

function GetArticles(pageLimitValue) {
    $.ajax(
    {
        url: "/Articles/Select",
        dataType: "json",
        data: { pageLimiter: pageLimitValue },
        async: true,
        beforeSend: function () {
            alert("before");
        },
        complete: function (data) {
            @Model = SOME_MAGIC_TRICKS
        }
    });
}

As you can see, in the complete event are words SOME_MAGIC_TRICKS. In this place I'd like to set @Model obtained from controller. Is it possible at all? How to insert data from ajax result to view model (it's null by default)?

Upvotes: 1

Views: 767

Answers (2)

Jeyhun Rahimov
Jeyhun Rahimov

Reputation: 3787

You can send data doing serialize it may be like:

public ActionResult Select(int pageLimiter)
{
    var viewModel = new ArticlesViewModel
                            {
                                Articles = this.Service.GetArticles(0, 0, 0),
                                ArticlesTotal = this.Service.CountArticles(0),
                                Pages = new List<string>
                                            {
                                                "1", "2", "3"
                                            }
                            };

    string myjsonmodel = new JavaScriptSerializer().Serialize(viewModel );
    return Json(jsonmodel = viewModel, JsonRequestBehavior.AllowGet);
}

dont forget using using System.Web.Script.Serialization;

Edit:

To deserialize object try this:

@{
 JavaScriptSerializer jss= new JavaScriptSerializer();
 User user = jss.Deserialize<User>(jsonResponse); 
}

Upvotes: 0

Dima
Dima

Reputation: 6741

You are trying to modify server variable from client's code. It's not possible.

If you want to re-render your page's content on complete, you may render <ul class="articleList"> with PartialView and return same partial view instead of JsonResult. Further, oncomplete handler will update your <ul class="articleList"> with returned content.

Upvotes: 1

Related Questions