Retrieving selected item text within a JsonResult function - c#

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 = new 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.

Related

Pass kendo grid model in Ajax call

I need to pass kendo grid model (on save event) to the server side in an ajax call. How can i do that? Tried the following
function onSave(e) {
var keys = Object.keys(e.values);
var colName = keys[0];
var alignment;
var mapHeaderId = $('#ddlMaps').val();
var yearId = $('#ddlYear').val();
$.get("#Url.Action("CalculateFormattingForResult", "Maps")", { studentId: e.model.studentid, colId: colName, value: e.values[colName], mapHeaderId: mapHeaderId, yearId: yearId,
model: JSON.stringify(e.model)
}, function (data) {}
}
My C# code is
public string CalculateFormattingForResult(int studentId, string colId, string value, int mapHeaderId, int yearId, string model) {
}
If someone is interested into why i am doing that..is because i need to get the latest edited values in the grid based on which i have to calculate/update other values in the grid.
UPDATE
I tried it with $.post and it worked but with post the problem is that probably i can only submit the form once however, i am only doing data validation on edit event of each cell...so i need to do it again and again. so my question is still there... how do i pass json string which is [kendo dataItem (row)] in ajax??
The problem was i had to put a $.post instead of $.get..found answer here:passing json in ajax
Also, as I mentioned in update, second time kendo grid model changes like this
originaljson + edited values as json
for example: firstname:"samra", surname:"abc" becomes firstname:"samra", surname:"abc" , firstname:"sarah", surname:"xyz"
In my case the newer values contained html divs (to format cells), so it was not getting posted!.

Get selected item of DropDownListFor and using it to create new list

Have some problems trying to solve this. Have two DropDownListFor where the first is populated with data and the second should be populated using the selected value from the first.
Lets say the first DropDownlist contains these data:
RoutesList;
Value = "CoOs", Text = "Copenhagen - Oslo",
Value = "StOs", Text = "Stockholm - Oslo",
Value = "OsCo", Text = "Oslo - Copenhagen"
In my razor view I'm trying to create a new list based on the selected value.
How do I get the selected value, lets say "StOs" and format it so it only contains the first two letters "St"? Trying to do this with C# and not Jquery.
My code
// Loads RoutesList to departureRouteSelectList
var departureRouteSelectList = Model.RoutesList;
// Finds selected value
var selectedItem = departureRouteSelectList.Select(x => x.Value);
// Create new selectList for returnRoute
List<SelectListItem> returnRouteSelectList = null;
I'm not sure if the "Select" command does what I want and getting the "StOs"?
Understanding what you want make me think this post will resolve your problem:
Can't get my DropDownListFor to select a selected SelectListItem item in a Dropdown menu

Setting the Selected Value of a Dropdown list in the View from the Controller Action

I have 5 dropdowns, which are basically displaying "Select", "Yes" and "No". Initially they are set to "Select". Once he user chooses something, I am storing the data in a cookie (with Jquery) and eventually passing this to the ViewModel so that I can use it in the Controller.
When the user refreshes the page, I want these dropdown lists to be populated again with the value I have in the ViewModel.
At the moment I have the following code :-
Inside the View I have
<%: Html.DropDownList("FirstQuestYesNo", ViewData["FirstQuestYesNoData"] as SelectList, new { #class = "normalDropdowns" })%>
and in my controller I have the following :-
var ddlYesNoData = new SelectList(new[]
{
new {ID="",Name=#Resources.GeneralTerms.GeneralTerms_Select},
new {ID="Yes",Name=#Resources.GeneralTerms.GeneralTerms_Yes},
new{ID="No",Name=#Resources.GeneralTerms.GeneralTerms_No},
},
"ID", "Name", 1);
//Refresh the YesNo dropdown with the correct vals
Dictionary<string, string> YesNoData = new Dictionary<string, string>();
YesNoData.Add("FirstQuestYesNoData", viewModel.FirstQuestYesNoValue);
YesNoData.Add("SecondQuestYesNoData", viewModel.SecondQuestYesNoValue);
YesNoData.Add("ThirdQuestYesNoData", viewModel.ThirdQuestYesNoValue);
YesNoData.Add("FourthQuestYesNoData", viewModel.FourthQuestYesNoValue);
YesNoData.Add("FifthQuestYesNoData", viewModel.FifthQuestYesNoValue);
foreach (var item in YesNoData)
{
ViewData[item.Key] = ddlYesNoData;
if (item.Value != null)
{
var selected = ddlYesNoData.Where(x => x.Value == item.Value).First();
selected.Selected = true;
}
}
So basically what I am doing is get the value of each dropdown from the viewModel, and then try to set that value inside my View. As a result of what I am doing, I am getting all the DropdownLists option as "Select" instead of the value inside my viewModel.
The problem is that I do not know how to "target" the specific DropDownList. How can I target the DropDown (in this case "FirstQuestYesNo") from the Controller using my code?
Thanks for your help and time.
In your controller action simply set the FirstQuestYesNo property to the corresponding value. For example:
ViewData["FirstQuestYesNo"] = "Yes"; // this value might come from a cookie
This will automatically preselect the option with value="Yes". Obviously this value will come from the cookie. You don't need any foreach loops.

Getting an ID of a value from dropdown list

Hey,
I Have three IQueryable lists which i concat together into one list to be displayed in the dropdown box. But now I want to get the id of what the user selected since there are 3 lists to choose from. Thanks
Example:
IQueryable<Store> stores= _storeRepository.FindAll().OrderBy(c => c.Description);
var storeList = stores.ToSelectList("StoreId", "Description", viewModel.StoreId.ToString());
IQueryable<Product> products = _productRepository.FindAll().OrderBy(j => j.Name);
var productList = products.ToSelectList("ProductId", "Name", viewModel.ProductId.ToString());
var viewList = storeList.Concat(productList).ToList();
viewModel.Lookups = viewList; //display in dropdown
if you question was i have 3 lists and the user choose one how can i know which one he chosen
Answer :
you give all three the same name and the value will change depend on which one the user have chosen
if your question was i want to send the id value with the selected list
Answer :
the server doesn't have any info about your html attributes
just the name attribute which maps to the action method parameter name and the value which maps to the parameter value , you can't know the id value and other attributes in the server
Example :
<input type="text" name="Title" id="SomeValue"/>
Will Map To :
public ActionResult Index(string Title)
the server will not recive id="SomeValue"
Solution :
What you can do is place a hidden field under every item with the value you want
instead of this way, after concatenating do this
viewdata["viewList"] = storeList.Concat(productList).ToList();
and view display items in dropdown like this
<%= Html.DropDownList("viewlist_id", (List<SelectListItem>)ViewData["viewlist"])%>
now use a submit button (if want to post the data to same action else use actionlink with routvalues if redirecting to different action,I am using here submit button)
<input type="submit" name="submit" value="submit" />
and in your action you can retrieve the posted data
var dropdown_id = Request.Form["viewlist_id"];
this way you will get the id of selected drop down. thanks
So i figured out how to have the values of different lists combined into one dropdown list will still being able to access its actual value or ID without concat or union- the code is a lot if anyone is interested i will go ahead and take the time to properly post it. Other than that, thank you everyone for offer your advise and help. Thanks
So this is how i went about my problem. In my Controller File - in my Get method after the button click this is what i did:
resultSummaryViewModel.Value = value;
resultSummaryViewModel.ReportFrame = new FramedViewModel();
if(value !="")
{
string viewValue = value.Substring(0, value.IndexOf("|"));
string viewType = value.Substring(value.IndexOf("|") + 1);
resultSummaryViewModel.ReportFrame.SourceURL =
WebPathHelper.MapUrlFromRoot(
string.Format(
"Reporting/ResultSummary.aspx?beginDate={0}&endDate={1}&Id={2}&viewType={3}",
resultSummaryViewModel.BeginDate, resultSummaryViewModel.EndDate, viewValue,
viewType));
}
var viewData = new Dictionary<string, string>();
viewData.Add("Schools", "|allschools");
viewData.Add("Classes", "|allclasses");
This is also connected to my display page aspx.cs which contains the actual lists i use to populate.

Convert my List<Roomtype> to SelectList for ASP. NET MVC DropDownFor<>, and get the correct values per option item

I have my class RoomType:
Int32 Id
String Name
String ColorCode
My viewmodel gets a List<Roomtype> RoomTypes which should be displayed in a dropdown.
Each dropdown option item should have: 1) as title the Name, 2) as value the Id, and 3) the style background-color #ColorCode.
My problems are how to convert this list correctly into a List<SelectListItem> as required by ASP.NET MVC's DropDownFor helper, and then to have the correct values inserted for each option.
I've tried to have a new readonly property in my viewmodel, which has a getter RoomtypeSelectList which returns new SelectList(RoomTypeList) but I can't get the correct properties to show (Name, Id, Background color).
I'd appreciate some help or pointers in the right direction...
In the view try something like this
<%=Html.DropDownList("userList", new SelectList((IEnumerable)ViewData["RoomTypes"], "Value", "Text",selectedValue)) %>
in your controller action you'd have
List<SelectListItem> roomTypesSelect = new List<SelectListItem>();
IList roomTypes = RoomTypeManager.GetAllRoomTypes();
RoomTypes currentRoomType = RoomTypeManager.GetCurrentRoomType();
bool isSelected = false;
foreach (RoomTypes roomTypes in roomTypes)
{
if (currentRoomType.Id == roomTypes.Id)
isSelected = true;
else
isSelected = false;
roomTypes.Add(new SelectListItem { Text = roomTypes.Name + " " +roomTypes.ColourCode, Value = roomTypes.Id, Selected = isSelected });
}
ViewData["RoomTypes"] = roomTypes;
The built in html helper methods do not allow you to generate style or title attributes for the select list items.
If you want to add these attributes, you'll need to create your own html helper methods, or just output the select list manually using a <% foreach ... %>.

Categories

Resources