w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Why would my Html.DropDownList yield a list filled with "System.Web.Mvc.SelectListItem" strings?
The constructor you are using treats its first argument as a list of objects that should be displayed in a list, and calls ToString on each of them to get both text and value for the corresponding list item. If these objects happen to be SelectListItem instances - it makes no difference, they are treated the same. SelectListItem.ToString is not defined and calls basic implementation, which is the string representation of the type. That is the why you are seeing list of "System.Web.Mvc.SelectListItem". In your situation you do not need to construct enumerable of SelectListItem objects, just use another constructor of SelectList: var model = new MyModel(); model.SelectedItemId = somevalue; model.PossibleItemsList = new SelectList( someSource, "FirstMember", "SecondMember", model.S

Categories : C#

What is the relationship between SelectListItem and SelectList
The relation is that SelectList implements IEnumerable<SelectListItem> which translated to a non technical language means that SelectList is a collection of SelectListItem or if you prefer SelectList is composed of multiple SelectListItems.

Categories : Asp Net Mvc

How to cast a custom model dropdownlist into a selectlist
Instead of casting it to a List<YeagerTechModel.Status[]> try just casting it to YeagerTechModel.Status[]. Arrays implement IEnumerable so it should be fine passing it to the SelectList.

Categories : C#

Options are empty in a second selectlist form field after selection an option in the first selectlist (Mechanize and Ruby)
However, after that, I print the second selectlist's options but I get an empty array: I am thinking this is because it is still parsing HTML from the initial pageload and isn't parsing HTML returned after the selectlist option was selected. The second select is probably populated by javascript. javascript can be used to listen for events on an html page such as selecting something, or changing the focus to another html element. When one of those events is triggered, a js program can then add elements to the page, like <option>'s. How can I access the second selectlist's options? Not with mechanize. You will need to use something that can execute javascript, like selenium: http://code.google.com/p/selenium/wiki/RubyBindings ...and you will need to know some

Categories : Ruby

Multiple Html.dropdownlistfor with the same selectlist, set selected value
Instead of just providing Model.Difficulties to the DropDownListFor helper try passing it: new SelectList(Model.Difficulties, object selectedValue) OR another overload that lets you specify the value and text field: new SelectList(Model.Difficulties, string dataValueField, string dataTextField, object selectedValue) Use one of these as the second argument for the DropDownListFor helper. Creating a SelectList from the List<SelectListItem> allows you to set the initially selected value.

Categories : Asp Net

Cannot get Dropdownlist to work properly
In your Controller Action, you should create the list of DropDownList options and pass them to your View in a ViewBag, or as a property of your ViewModel. Like below: public ViewResult Index(string searchString, string sortOrder = "Asc") { var users = from u in db.TBL_SYS_USER select u; if (!string.IsNullOrEmpty(searchString)) { users = users.Where(x => x.USER_FIRST_NAME.ToUpper().Contains(searchString.ToUpper())); } switch (sortOrder) { case "Desc": users = users.OrderByDescending(u => u.USER_FIRST_NAME); break; default: users = users.OrderBy(u => u.USER_FIRST_NAME); break; } PopulateFieldDropdownList(""); var sortOrderOptions = new List<SelectListIt

Categories : Asp Net Mvc

Assigning value to @Html.Hidden from value of @Html.DropDownList in MVC3
To solve this you can either Use a @Html.DropDownListFor instead of @Html.DropDownList for both dropdown lists. For this you need to change the viewbags into your model's properties. If you want to use ViewBag and your hidden fields, in the on change event of dropdown assign the selected value of drop downs to corresponding hidden fields. eg: $('#list').change(function(){ $('#Smth_Description').val($('#list:selected').val()); });

Categories : Asp Net Mvc

SelectList with Dictionary, add values to the Dictionary after it's assigned to SelectList
Try something horrendous like this: ((Dictionary<string, string>)mySelectList.Items).Add("keyC", "valueC"); It would be better if you just kept the reference to myDict around in your own code, though, rather than abusing their property. Note: It's very possible this doesn't work. I haven't tried it.

Categories : C#

update .html with @HTML helper DropDownList
Interesting use of Html helper injection... The Html.DropDownList generates multiple lines though, generating an unterminated javascript string. How do you plan to get around that? Why not inject it into a dummy script template div instead and have your JQuery simply copy it? <script id="template" type="text/template"> @Html.DropDownList("CmpAdrsSt.State", (IEnumerable<SelectListItem>)ViewBag._State) @Html.ValidationMessageFor(m => m.CmpAdrsSt.State) </script> Then copy using: $('#CmpMASttF').html($('#template').html()); I prefer this to trying to inject HTML into Javascript string literals, as this gives better separation of the UI from the code.

Categories : Jquery

@Html.Dropdownlist(x => x.id, new int) not working
You are declaring an object of type int and populating it with a List of SelectListItems, which will not work. I think you want something like this... You may have to make some modifications if x.Id is an int and all the dropdown values are strings, but I'm not sure. @Html.DropDownListFor(x => x.Id, new List<SelectListItem> { new SelectListItem() {Text = "asdad", Value = "1"}, new SelectListItem() {Text = "dfgdgd", Value = "2"}, new SelectListItem() {Text = "werwrwt", Value = "3"}}, "Choose")

Categories : Asp Net Mvc

MVC HTML.DropDownList set width
You don't need the @ before style and also you need to pass in the ViewData into the DropDownList source: @Html.DropDownList("dropDown_"+item.ConfigCode, (IEnumerable<SelectListItem>)ViewData["dropDown_"+item.ConfigCode] ,new { style = "width: 50px;" }) You only need to escape keywords with the @ symbol if they are C# keywords, for example class

Categories : HTML

asp.net mvc html helper Dropdownlist issues
First, that's not a check box. That's a drop down list. Asking questions with correct information is important, or you will get the wrong answers. Second, this is not possible, and it has nothing to do with MVC, this is done by the browser. There's no way to make the browser submit "null" when you're actually submitting something. There is no concept of "null" in an http post. The only way you get null is if the value is not posted at all. Otherwise, the model binder could not know the difference between an actual null and when you actually wanted to post an empty string. You can't even create a custom model binder, because you're bypassing model binding by going directly to the forms collection.

Categories : Asp Net Mvc

Not able to assign selected value to Html.Dropdownlist MVC 4
Follow the below sample which i have did to show the selected value in dropdown, @Html.DropDownListFor(model => model.Country, (IEnumerable<SelectListItem>)ViewData["CountryList"], new { id = "card_country", @class = "donation-ddlcountry" }) `public void CountryList(string countryCode) { string path = Server.MapPath(@"~Country.xml"); IEnumerable result = from x in XElement.Load(path).Elements("country") select x; var listItems = new List<SelectListItem>(); foreach (var xElement in result) { listItems.Add(new SelectListItem { Text = xElement.Element("text").Value, Value = xElement.Element("value").Value });

Categories : C#

Html.DropDownList disable if it is Empty
@if (@ViewBag.UserName.Items.Count == 0) { @Html.DropDownList("UserName", null, string.Empty, new { @disabled=true}) } else { @Html.DropDownList("UserName", null, string.Empty) } You could use @readonly aswell, instead of @disabled.

Categories : C#

how to access the Selected value of an HTML.Dropdownlist
You want to use this signature of the DropDownList method: public static MvcHtmlString DropDownList( this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, string optionLabel ) And, this constructor of the SelectList class: public SelectList( IEnumerable items, Object selectedValue ) So, do it like this: @Html.DropDownList("siteName", new SelectList(ViewBag.sites, Model.Resource.CI.SiteDefinition.SDOrganization.NAME), "None") But, make sure your ViewBag.sites does not have any null values. Also, follow the standard naming conventions. Use "SiteName", instead of "siteName", and "Sites" instead of "sites". And, most important of all, add SiteName to your ViewModel, and use the Strongly-Typed version of DropDownList, like below:

Categories : Asp Net Mvc

@html.dropdownlist not populating the selected value
In ASP.NET MVC controller actions must return ActionResults. In your case you could return JSON: public ActionResult GetRegionList(int id) { var objRegionList = new List<Region>(); objRegionList.Add(new Region { ID = "0", Name = " " }); if (countryid != 0) { int countryid = ID; using (var conn = new SqlConnection("YOUR CONNECTION STRING COMES HERE")) using (var cmd = conn.CreateCommand()) { con.Open(); cmd.CommandText = "USP_ProcedureName"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Id", countryid); cmd.Parameters.AddWithValue("@Mode", "Region"); using (var dr = cmd.ExecuteReader()) { while (dr.Read())

Categories : C#

How to get Html.DropDownList() to retain selected value on postback?
Have you tried setting autopostback property to true? Dropdown Box has the property autopostback whcih if set to true fires an event. So when ever user selects a different value in the combo box, an event will be fired in the server. i.e. a request will be send to the server Reference

Categories : Asp Net

Creat html table on dropdownlist value change?
Here is a sample code for AJAX. so you can modify it on what ever language you were using. <!DOCTYPE html> <html> <head> <script> function showCustomer(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getcustomer.asp?q="+str,true); xmlhttp.send(); } </script> </head <body> <form> <select name="customer

Categories : Java

How to access js variable in view, Html.DropDownList?
You can set selected value for dropdown whenever variable changes: ie; var orgCode = ""; $("#orgs").change(function () { var org = document.getElementById("orgs"); orgCode = org.options[org.selectedIndex].value; $('#docs').val(orgCode); });

Categories : Javascript

@Html.DropDownList not binding selectedValue in Edit
Write: @Html.DropDownListFor(model => model.OfficeSiteId, ViewBag.OfficeSiteId as SelectList, new {@class = "chzn-select"}) in place of: @Html.DropDownList("OfficeSiteId", ViewBag.OfficeSiteId as SelectList, new {@class = "chzn-select"}) AND Write: ViewBag.OfficeSiteId = new SelectList( _unitOfWork.OfficeSiteRepository.Get(), "Id", "Name"); in place of: ViewBag.OfficeSiteId = new SelectList( _unitOfWork.OfficeSiteRepository.Get(), "Id", "Name", model.OfficeSiteId);

Categories : Asp Net Mvc

How To Correctly Use the HTML.DropDownList with Ajax Calls for MVC
If anyone cares its pretty simple the Ajax function's main work cant call a controller action that updates the view. However the Ajax success call can assuredly call one of the controller's ActionResults to update the view and thereafter its related Partials in that view ,,, the controller action in tha main part of the ajax call that DOES WORK needs to be marked EmptyResult & [HttpPost] The controller action that really fires up an ActionResult to update your view ,, in my case, just returns the view and the newly modified model... and again note its called by the Success function of the previous cited ajax function The last code posting above pretty much covers it all

Categories : Ajax

MVC3 Razor HTML.DropDownList calculated field
$(document).ready(function(){ var total = parseInt($('#MonthlyFeeId').val()) + parseInt($('#ExamFeeId').val()) }); total will have the sum of your two dropdown values.

Categories : Asp Net Mvc

Html.Dropdownlist selected value is not posted back to the Controller from view
On your action Create, [HttpPost] version, in which variable are you expecting to see the value of your selected name? You've named your <select> element with id = "orgz", but you don't have a parameter to your action method named "orgz". Edit: When you do: @Html.DropDownList("orgz", (SelectList)ViewBag.orgz) You're going to end up with HTML like this: <select id="orgz" name="orgz">...</select> When the form is posted back to the controller action, it will try to find a variable called "orgz" that it will put the selected item from your <select> element into. You are missing this. Try changing your [HttpPost] version of Create to include an "orgz" variable: public ActionResult Create(TABLE_CODES dp, int orgz) { // orgz will contain the ID of the select

Categories : Asp Net

Html.dropdownlist does not display the default/selected value in the dropdown field
You need to set the selected id within the controller like this: var list_managers = list_managers.Select(x => new { Value = x.ID.ToString(), Text = x.Name }) .ToList(); ViewBag.managers = new SelectList(list_managers, "ID", "NAME", id); And change your view to: @Html.DropDownList("dpMANAGER", (SelectList)ViewBag.managers)

Categories : C#

How do I parse a dropdownlist returned as a HTML string in Javascript/jQuery?
Wrap the string in a jQuery selector: $(function() { var $select = $("<SELECT id=ddl_Freq name=ddl_Freq><OPTION selected value=AN>Annually</OPTION> <OPTION value=BM>Bi-Monthly</OPTION> <OPTION value=MO>Monthly</OPTION> <OPTION value=OT>One Time</OPTION> <OPTION value=QT>Quarterly</OPTION> <OPTION value=WE>Weekly</OPTION></SELECT"); console.log($select.val()); }); Here is an example fiddle

Categories : Javascript

Passing additional fields with a HTMl.DropDownList from my view to action method
You could get at all those values by passing the FormCollection into you action. [HttpPost] public ActionResult AssignPermisionLevel2(FormCollection collection) { // Get Post Params Here var list = collection["PermisionLevelID"]; var assetTypeId = collection["AssetTypeID"]; var securityRoldId = collection["SecurityRoleID"]; }

Categories : C#

Prevent duplicate data from appear in another dropdownlist when it is selected by another dropdownlist
You can use Cache to achieve this.Like this protected void bindDdls() { DataTable dt = new DataTable(); try { ddlpid1.Items.Clear(); ddlpid2.Items.Clear(); using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI")) { connAdd.Open(); var sql = "Select policeid from PoliceAccount where status ='available' and handle ='offcase' and postedto='" + ddllocation.SelectedValue + "'"; using (var cmdAdd = new SqlDataAdapter(sql, connAdd)) { DataSet ds2 = new DataSet(); cmdAdd.Fill(ds2); dt = ds.Tables[0]; if (dt.Rows.Count > 0) { ddlpid1.DataSource = d

Categories : C#

Bind dropdownlist based on the selected value of another dropdownlist
If you want to use ajax control toolkit then here is the link http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/CascadingDropDown/CascadingDropDown.aspx Else you want to fill it from jquery or javascript here is the link http://www.mikesdotnetting.com/Article/97/Cascading-DropDownLists-with-jQuery-and-ASP.NET But if you go with the second link then you will have some security issue. Invalid postback or callback argument. When dropdown list populated with jquery and there is a postback

Categories : Javascript

Value of dropdownlist in asp.net disappears after changing the value of dropdownlist by javascript
It's dissapearing because you are binding the data on the server-side initially and when you make the ajax request to insert the new record into the dropdownlist, the ViewState for the DropDownList had no knowledge of this new value and therefore renders what it had before.

Categories : C#

Add new item in dropdownlist by getting id from dropdownlist object in jquery
You have to do this: $('#' + mySelect).append($('<option selected="selected"></option>').val(val).html(text)); because you just saved the id as a String and no jQuery-Object

Categories : Jquery

asp. net populate dropdownlist using javascript when a dropdownlist is change
When Dropdownlist1 is changed get that element which is selected by using following script <script type="text/javascript"> $jq14(document).ready(function () { $jq14("#Dropdownlist1").change(function (e) { window.location = "@Url.Content("~/Controller/ActionMethod/?id=")" + $jq14(this).val(); }); }); </script> Then in your controller action method receive that value and put it into ViewBag object like ViewBag = id; Then finally in your view get that ViewBag value in your Dropdownlist2 to as seeder for loop or list population

Categories : C#

ASP.NET MVC 3 List to IEnumerable
You could provide callbacks that obtain the key and the value and then use those. Apart from that you can create it as an extension method: Extension method: public static List<SelectListItem> ToSelectList<T>(this List<T> Items, Func<T, string> getKey, Func<T, string> getValue, string selectedValue, string noSelection, bool search = false) { List<SelectListItem> items = new List<SelectListItem>(); if (search) { items.Add(new SelectListItem { Selected = true, Value = "-1", Text = string.Format("-- {0} --", noSelection) }); } foreach (var item in Items) { items.Add(new SelectListItem { Text = getKey(item), Value = getValue(item)

Categories : Asp Net Mvc

SelectListItem with data-attributes
You'll have to extend SelectListItem, and then extend DropDownListFor to use the extended SelectListItem. Have a look at this solution: Adding html class tag under <option> in Html.DropDownList

Categories : Asp Net Mvc

There is no ViewData item of type 'IEnumerable' that has the key 'SelectedCityName'
Inside your POST action you are rendering the same view in case of error (return View(model);). But you forgot to assign the City and Ward properties, the same way you did in your GET action and they will be null when this view is rendered. So: // If we got this far, something failed, redisplay form // and don't forget to rebind City and Ward model.City = ILocaRepo.Cities.ToList().Select(x => new SelectListItem { Value = x.CityID.ToString(), Text = x.CityName, }); model.Ward = ILocaRepo.Wards.ToList().Select(x => new SelectListItem { Value = x.WardID.ToString(), Text = x.WardName, }); // Now we can safely redisplay the same view return View(model); The reason why those 2 properties are null inside your POST action is pretty simple and lies into the design of HTM

Categories : Asp Net Mvc

There is no ViewData item of type 'IEnumerable' that has the key 'PestType'
You have @Html.DropDownList("PestType", String.Empty), but the second param needs to be an IEnumerable<T>. You will need the list of your pest in the model, and then use model.Pests for example where Pets is an IEnumerable. EDIT: Based on comment... But I want to display just the various types of pest (Dog, Cat, etc) not all the pests that are in my database OK, are these categorised, could you write something like (hand written so check syntax).. var pests = (from _context.Pests.Where(p => p.CategoryId == 1) select p.PestName).ToList(); If you need to get a IEnumerable for the enum (since I'm not sure what the DB looks like), you can use... Enum.GetValues(typeof(PestType)) .OfType<PestType>() .Where(p => p == ??);

Categories : C#

how can i use id of option in selectlist
Please make sure to use an ID only once per page. An ID is a UNIQUE identifier of some element. I guess that "select" or "dropdown" aren't really unique page elements, so think of better names, for example "profile_picture_select" and "product_image_select". Also, don't use inline javascript (onclick="getValue()"). EXAMPLE HTML <select id="function_select"> <option>profile_picture_select</option> <option>product_image_select</option> </select> <div id="profile_picture_select">profile_picture_select</div> <div id="product_image_select">product_image_select</div> JavaScript (jQuery) (use indentation) $(function () { // Same as $(document).ready(). $("#profile_picture_select").hide(); // B

Categories : Javascript

Some clarification on using selectList please?
Don't use view bag, rather pass your data using a view model. Don't pass in your domain model, use a view model. Lets start with your action method. Lets call it YourActionMethod. It creates an instance of your view model and populates the user list with your users. How you populate your users in the sevice layer depends entirely up to you. public ActionResult YourActionMethod() { YourViewModel viewModel = new YourViewModel { Users = userService.FindAll() }; return View(viewModel); } Your view model can look like this (partial): public class YourViewModel { public int UserId { get; set; } public IEnumerable<User> Users { get; set; } } Create a domain model to represent your users. Your user domain model could look something like thi

Categories : Asp Net Mvc

how to refill another dropdownlist when i change the first dropdownlist value?
Listen to the change event of first dropdown, read the selected value, send that to an action method which returns JSON data for the content of second dropdown. read JSON And load to the second dropdown. $(function(){ $("#CountryDropdDown").change(function(e){ var country=$(this).val(); $.getJSON("@Url.Action("States","Home")?id="+country,function(data){ var items=""; $.each(data,function(index,item){ items+="<option value='"+item.ID+"'>"+item.Name+"</option>"; }); $("#States").html(items); }); }); }); Assuming your Homecontroller has an action method called States which accepts an id and return JSON in the below format [ { "ID": "1", "Name": "MI" }, { "ID": "2", "Name": "NY" } ] EDIT : As p

Categories : Asp Net

Dropdownlist Onchange Show other Dropdownlist
Try this, Your problem is in if condition your are not using == function getData(dropdown) { var value = dropdown.options[dropdown.selectedIndex].value; if (value == 'emlak'){ document.getElementById("emlak").style.display = "block"; document.getElementById("vasita").style.display = "none"; } if(value == 'vasita'){ document.getElementById("vasita").style.display = "block"; document.getElementById("emlak").style.display = "none"; } } Demo Update Demo

Categories : Javascript

There is no ViewData item of type 'IEnumerable' that has the key 'aboutcar.Doors'
Check your [HttpPost] method. I had the same error. It cause i forgot to create ViewBag.Property in else block of my [HttpPost] Method. For example: [HttpPost] public ActionResult Edit(Model model) { if (ModelState.IsValid) { //TO DO } else { ViewBag.Doors = new SelectList(new[] { new {ID = 1, Name="1-Door"}, new {ID = 2,Name="2-Doors"}, new {ID = 3,Name="3-Doors"}, new {ID = 4,Name="4-Doors"}, new {ID = 5,Name="5-Doors"}, new {I

Categories : Asp Net Mvc



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.