Laziale
Laziale

Reputation: 8225

Passing JSON data from controller action to a razor view

I would like to know how can I pass data from controller to view in mvc3 razor. The view is in .cshtml file. I have a variable in the controller where I am storing the data I need to push to the listbox control in the view.

var results = data.Select(item => new { id = item, label = item.Value, value = item.Key });

Doing this:

return Json(results, JsonRequestBehavior.AllowGet);

Gives me only a popup with the data which needs to be pushed to the listbox:

result

In the view the listbox resides in accordion control:

    <div id="accordion">
    @{int i=0;}
        @foreach (var item in Model.Parameters)
        {
            <h3><a href="#">@Html.LabelFor(m => item.Name, item.Prompt)</a></h3>
            <div>                   

                <div class="editor-field">
                    <select multiple id="@("Select" +item.Name)" name="@("Select" +item.Name)"></select>                           
                </div>                                     
            </div>
            i++;
        }         
    </div>

So, I would like to know what should I do to push the items to the listbox instead of showing a popup for the control

Beginner in MVC, Thanks for your understanding. Thanks in advance, Laziale

EDIT: Json format output

{System.Linq.Enumerable.WhereSelectListIterator<System.Collections.Generic.KeyValuePair<string,string>,<>f__AnonymousType1<System.Collections.Generic.KeyValuePair<string,string>,string,string>>}

Upvotes: 1

Views: 3843

Answers (1)

Baz1nga
Baz1nga

Reputation: 15579

returning JSON to your razor view is probably not the best method. I would suggest use a viewModel which is a c# class by itself.

namespace Test
{
    public class ViewModel
    {
        public bool GivingAPresentation { get; set; }
    }
}

public class MyController: Controller
{

    public virtual ActionResult Index()
    {
        var model=new ViewModel(){GivingAPresentation =true;}
        return View(model);
    }

}

Your view code:

@model Test.ViewModel <!-- Note the full namespace -->

<br>GivingAPresentation: @Model.GivingAPresentation </br>

If you are forced to work with a JSON object that is returned from your action then you need to deserialize it first and then work with that object. you can read this post http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx on how to parse JSON to a c# dynamic object.

Let me know if that helps.

Upvotes: 2

Related Questions