开发者

Retrieving selected item text within a JsonResult function

I am creating an MVC project with a table using the JQGrid plugin. I would like to use a DropDownList to allow the user to specify a value, that will be used in an SQL query to retrieve specific data from the table. I.e. user can select a country from the list, and the table will display items only from that country.

My problem is, that I cannot figure out how to retrieve the selected item from the DropDownList, within my data bind function for my table, within my controller class.

DropDownList in the View

<%= Html.DropDownList("Countries")%>

Setting up the DropdownList in my controller

//dt is a DataTable which holds the values for my list
List<SelectListItem> countries = n开发者_C百科ew List<SelectListItem>();
for (int i = 0; i < dt.Rows.Count; i++)
    countries.Add(new SelectListItem { Text = dt.Rows[i][0].ToString(), Value = "" + i });

JsonResult DataBind() method where I would like to access the selected value

public JsonResult Charges_DataRequested()
{
    string country = "Dropdownbox Selected Text";
}

The problem seems to be that within a JsonResult function I don't have access to the ViewData or my ViewModel, which always seem to be null when I try and access them. I am very new to MVC and web development, any advice would be very welcome.


Thanks for the answer, it put me on the right track. I realized that the grid also has a postdata parameter. I was able to create a javascript postback function for my dropdownlist, and call the jqGrid 'setGridParam' function to add my dropdownlist text to the grid postdata. I could also trigger a grid reload, and grab the string in my controller Jsonresult function.

The Javascript

$('#Countries').change(function() {
        var value = $("#Countries option:selected").text();
        $("#ChargesGrid").setGridParam ({
            postData:{
                selectedCountry:$("#Countries option:selected").text()}
        });

        $("#ChargesGrid").trigger("reloadGrid");
        alert(value);
    });

The controller

public JsonResult Charges_DataRequested(string selectedCountry)
    {
        string country = selectedCountry;
    }


jqGrid has got a userdata property where you could store this data so it would be available on post. It may mean you'd have to update this dropdown changes.

jQuery("#GridId").getGridParam('userData').SelectedText

I've only used this the other to set data on loading but think it could work the other way around for you. I would have set the SelectedText above in a controller action when creating the grid json as

userdata = new { SelectedText = "SomeValue" }

The only trouble would be if it were a private set equivalent within the jqGrid code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜