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.
Related
As I am new to MVC framework, I have been spending a couple of hours to generate a check box list in a View file. Finally, I could figure it out well. Here is my code:
#foreach (var item in Model.GetRoleNames)
{
#Html.CheckBox("chk_" + item.Value, new { value = item.Value })#item.Text<br />
}
But, I need to detect which of them is selected and if all the ckeckboxes are left unchecked, then preventing some operations.
Question: How can I get the checked items when I am within a controller action?
As the others said, you should use a Boolean value as the second parameter to CheckBox to indicate the checked status. A bit of string manipulation should help you get the ids of the selected check boxes..
First lets change the way the checkbox helper is used
<div id='myCheckboxDiv'>
#foreach (var item in Model.GetRoleNames)
{
#Html.CheckBox("chk_" + item.Value, false)#item.Text<br />
}
</div>
As you can see, I have set the second parameter to false and wrapped the mix in a div
And, when you want to get the ‘values’ associated with the selected checkboxes
var values = $(‘# myCheckboxDiv’).find('input:checkbox:checked').map(function () {
// get the name ..
var nameOfSelectedItem = this.attr('name');
// skip the ‘chk_’ part and give me the rest
return nameOfSelectedItem.substr(4);
}).get();
I am assuming item.Value to be a number. If its is not, please remove the white spaces using C#
This should be an easy one, but without ViewState, I'm clueless here (I've been babied with WebForms for too long, I know!).
My scenario:
View
#foreach (var product in Model.Products)
{
<tr>
<td>#Html.ActionLink("Compare", "Compare", new { id = product.ProductId })</td>
</tr>
}
Controller
public ActionResult Compare(int id = 0)
{
var product = SelectProduct(id); // selects the product from a list of cached products.
if (product != null)
{
// _productDetails is a Model specifically for my View.
_productDetails.ComparedProducts.Add(product);
}
return View("Index", _productDetails);
}
Obviously, when you click on "Compare" for each item, it'll add to the the ComparedProducts list. But, with there being no ViewState, this will get cleared on every page refresh and lose the last product. I want products to be kept in this ComparedProducts list, but how?
I'm guessing they need to be appended to the querystring, so /Carousel/Compare/?id=2122,1221,1331,1333 etc. If so, how is this possible?
Thanks in advance.
Updated
If I did want to go the query string route, how do I do this?
I've tried:
<td>#Html.ActionLink("Compare", "Compare", new { id = product.ProductId, compared = Model.ComparedProducts.Select(a => a.ProductId) })</td>
But that brings out:
compared=System.Linq.Enumerable%2BWhereSelectListIterator`2[Product%2CSystem.Int32]
Which I'd expect really. I guess I'd make yet a further ViewModel property and simply store the Compared Id's in there to not have much business logic within my View?
+1 for your relationship with webforms :)
I think from now on, you can start to keep state in the other ways you already know from webforms like Session State: http://msdn.microsoft.com/en-us/library/ms178581(v=vs.100).aspx
You are also right on the querystring, after all, if you want to keep things simple, is better to use the simplest methods , for instance:
<url>?reference=123&compare=456
EXAMPLE
you need the first action as HttpGet and now this one as httpPOST
[HttpPost]
public ActionResult Compare(myModel model)
{
var product = SelectProduct(model.reference); // selects the product from a list of cached products.
if (product != null)
{
// _productDetails is a Model specifically for my View.
// you can always update the model you got in the first place and send it back
model.ComparedProducts.Add(product); //
}
return View("Index", model);
Your view should react according to empty properties to display
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.
If i got a list of checkbox in a View, and this list came from Enum (flags). If my checkbox as all the same name, did my controller will update automaticly my Enum (flags) values in my ViewModel with multiple selection ?
Suppose i get in my View
<% foreach (var t in Enum.GetValues(typeof(FoodType)))
{
Response.Write(t.ToString() + " ");
%>
<input type="checkbox" name="TypeOfFood" value="<%:(int)t %>" />
<% }%>
My Controller working like this
public ActionResult Manage(FoodEntity food)
{
}
If i check many check box when i look then FoodType property in my foodEntity, only the value of the first checkbox is selected, but my enum is a flag... what i need, if i want support flag ?
thanks.
Unfortunately no.
It will just grab the first checked value and assign that to your value field.
That would be a pretty cool feature though.
Heres a quick way to get the value you're looking for back into your model:
int newEnumValue = Request.Form["CheckBoxField"].Split(',').Aggregate(0, (acc, v) => acc |= Convert.ToInt32(v), acc => acc);
I have the following code which is meant to populate a dropdown with a bunch of integer values and make the currently selected value (in this case, 13) be the selected item.
I've used the same technique but for string values and it works great, remembering each time when I get to the view what the current value is.
In controller:
var x = new[] { 1, 2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
ViewData["Field"] = new SelectList(x, 13);
In view:
<%=Html.DropDownList("Field", (IEnumerable<SelectListItem>)ViewData["Field"])%>
When I debug and watch the ViewData["Field"] object, it does have a selectedValue of 13 and so it must be reaching the View but getting ignored there as all I see on the page is a dropdown with the values 1 to 15, but with 1 showing (none selected so shows the first one)
Is this a bug or am I doing something really stupid?
Thanks
Graeme
I seem to recall that it doesn't actually use the Selected property of the SelectList element. I usually have one ViewData item be the select list and another be the selected value.
Controller:
var x = new[] { 1, 2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
ViewData["Fields"] = new SelectList(x);
ViewData["Field"] = 13;
View
<%= Html.DropDownList("Field", (IEnumerable<SelectListItem>)ViewData["Fields"] ) %>
This was happening to me! I was pulling my hair out for hours, but I eventually figured it out. In my case I was creating a drop-down list like this:
<%= Html.DropDownList("bookId", Model.ProductMenu, new { onchange = "goToBook();" })%>
And it was not printing the selected option. But the dropdown right next to it was working fine:
<%= Html.DropDownList("segmentIndex", Model.SegmentMenu, new { onchange = "goToSegment();" })%>
They were being generated the exact same way in the controller, and the debugger would always show the properly selected value as the view was returned. So what the heck?
The difference was in the view itself. "bookId" in my app happens to be a route/querystring value and segmentIndex is not. Simply changing the name "bookId" in the view to "bookIdBLAH" fixed it!