leora
leora

Reputation: 196861

How to create this JSON in my ASP.Net MVC controller?

I am using jqGrid with a multiselect field. I have a demo that works fine using this code:

{
    name: "Subject",
    index: "Subject",
    width: 120, 
    formatter:'select',
    editable: true,
    edittype:'select',
    editoptions: {
        value: '1:sport;2:science',
        multiple: true,
        size: 2
    },
    editrules: { required: false} 
},

But this JSON is hard coded with the multiselect options. I'm trying to find a way where I can return the data that is now hardcoded as:

 '1:sport;2:science'

to come from a controller action in my MVC code. Is this possible?

Upvotes: 1

Views: 1003

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039478

You could use have your controller action return a JsonResult:

public ActionResult Foo()
{
    var data = "1:sport;2:science";
    var model = new
    {
        name = "Subject",
        index = "Subject",
        width = 120,
        formatter = "Select",
        editable = true,
        edittype = "select",
        editoptions = new
        {
            value = data,
            multiple = true,
            size = 2
        },
        editrules = new
        {
            required = false
        }
    };
    return Json(model, JsonRequestBehavior.AllowGet);
}

In this example I have used an anonymous type but you could define a view model that matches this structure and then return an instance of this view model.

Upvotes: 4

Alex
Alex

Reputation: 448

Like this:

var ms = "";

$.get('pathtomvc', function(txt) {
  ms = txt;
});

// your code goes here
{
name: "Subject",
index: "Subject",
width: 120, 
formatter:'select',
editable: true,
edittype:'select',
editoptions: {
    value: ms,
    multiple: true,
    size: 2
},
editrules: { required: false} 
},

Upvotes: -2

Related Questions