Search Results

Search found 145 results on 6 pages for 'selectlist'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • How can I add an item to a SelectList in ASP.net MVC

    - by Barrigon
    Basically I am looking to insert an item at the beginning of a SelectList with the default value of 0 and the Text Value of " -- Select One --" Something like SelectList list = new SelectList(repository.func.ToList()); ListItem li = new ListItem(value, value); list.items.add(li); Can this be done? Cheers

    Read the article

  • Insert value into selectlist

    - by William
    I need to insert a value into a selectlist. It isn't the "0" value (i.e. the first one that shows) but the next one which would be "Other". This is then used to display an "Other" textbox. My question is similiar to link text. EDIT: I don't know if this will help but here is the code: SelectList Titles; ViewData["TitleIsOther"] = TitleIsOther(Case); if ((bool)ViewData["TitleIsOther"]) { Titles = new SelectList((LookupCollection)this.LookupRepository.FetchByCategory(true, 0, 0, false, (int)Enums.LookupCategory.CaseTitles, _LoggedInUser.AccountId), "Id", "Name", "-1"); } else { Titles = new SelectList((LookupCollection)this.LookupRepository.FetchByCategory(true, 0, 0, false, (int)Enums.LookupCategory.CaseTitles, _LoggedInUser.AccountId), "Id", "Name"); } ViewData["Titles"] = Titles; The selected value of "-1" would be the "Other" option.

    Read the article

  • SelectList in Asp-mvc and data from the database

    - by George
    Hello guys. I'm having some troubles with SelectList in ASP.MVC. Here is the issue: I have a Create View and begind a ViewModel model. The page load just fine (GET verb). But when posting, something happens, and my model is considered invalid, and it cannot insert. Here's what i've tried so far. public class DefinitionFormViewModel { private Repository<Category> categoryRepository = new Repository<Category>(); public Definition ViewDefinition { get; private set; } public SelectList Categories { get; private set; } public DefinitionFormViewModel(Definition def) { ViewDefinition = def; // here i wanted to place it directly, like shown in NerdDinner Tutorial // new SelectList(categoryRepository.All(),ViewDefinition.Category); Categories = new SelectList(categoryRepository.All(), "CategoryId", "CategoryName", ViewDefinition.CategoryId); } } // pageview which inherits DefinitionFormViewModel <div class=editor-field"> <%= Html.DropDownList("Category",Model.Categories) %> <%= Html.ValidationMessageFor(model => Model.ViewDefinition.Category) %> </div> // controller methods [Authorize] public ActionResult Create() { Definition definition = new Definition(); return View(new DefinitionFormViewModel(definition)); } [AcceptVerbs(HttpVerbs.Post), Authorize] public ActionResult Create(int id,Definition definition) { Term term = termRepository.SingleOrDefault(t => t.TermId == id); if (term == null) { return View("NotFound", new NotFoundModel("Termo não encontrado", "Termo não encontrado", "Nos desculpe, mas não conseguimos encontrar o termo solicitado.", "Indíce de Termos", "Index", "Term")); } else { if (ModelState.IsValid) { try { definition.TermId = term.TermId; definition.ResponsibleUser = User.Identity.Name; UpdateModel(definition); term.Definitions.Add(definition); termRepository.SaveAll(); return RedirectToAction("Details", "Term", new { id = term.TermId }); } catch (System.Data.SqlClient.SqlException sqlEx) { ModelState.AddModelError("DatabaseError", "Houve um erro na inserção desta nova definição"); } catch { foreach (RuleViolation rv in definition.GetRuleViolations()) { ModelState.AddModelError(rv.PropertyName, rv.ErrorMessage); } } } } return View(new DefinitionFormViewModel(definition)); } I'm sorry about the long post, but I cant figure this out. I got no graphic errors or exceptions. My execution terminates in if (ModelState.IsValid). Thanks for your time George

    Read the article

  • WatiN SelectList Methods - Page not refreshing/actions not being fired after interacting with a sele

    - by Chad M
    Preface: If you don't care about the preface, skip down to the section marked "Question." Hi, Recently my company has upgraded to the latest version of WatiN for its test automation framework. We upgraded to avoid a problem where interacting with a select list would cause an ACCSES DENIED error. This error seems to be a product of the fact that our web application reloads the page it is on (which sits in a frame which sits in a frameset) with new fields after certain select lists options are selected. It could also be that our framework, which wraps around WatiN, often does actions on the same SelectList after the page refresh (I'm still looking into this, I'm new to the framework). The new version of WatiN does solve the ACCESS DENIED error, but also seems to stop select lists from firing the action that causes the page to reload w/ its new options. In fact, if you use WatiN to make the selection, the select list won't work correctly, even if manually interacted with, until the page has been forced to refresh. Question: When selecting an option in a SelectList using the newest WatiN code, the event that causes our web app's page to reload with new fields/values does not execute. What are some possibilities that could cause this? The term i've seen used most often to describe the refreshing that occurs when our select lists are used is "double post-back". Many thanks, Chad

    Read the article

  • How can i get this ASP.NET MVC SelectList to work?

    - by Pure.Krome
    Hi folks, I create a selectList in my controller, to display in the view. I'm trying to create it on the fly, sorta thing .. like this... myViewData.PageOptionsDropDown = new SelectList(new [] {"10", "15", "25", "50", "100", "1000"}, "15"); It compiles, but the output is bad... <select id="PageOptionsDropDown" name="PageOptionsDropDown"> <option>10</option> <option>15</option> <option>25</option> <option>50</option> <option>100</option> <option>1000</option> </select> Notice how no item is selected? How can i fix this?? Update Just bumping this ... issue still outstanding :(

    Read the article

  • C# mvc 3 using selectlist with selected value in view

    - by Rob
    I'm working on a MVC3 web application. I want a list of categories shown when editing a blo from whe applications managements system. In my viewmodel i've got the following property defined for a list of selectlistitems for categories. /// <summary> /// The List of categories /// </summary> [Display(Name = "Categorie")] public IEnumerable<SelectListItem> Categories { get; set; } The next step, my controller contains the following edit action where the list of selectlistitems is filled from the database. public ActionResult Edit(Guid id) { var blogToEdit = _blogService.First(x => x.Id.Equals(id)); var listOfCategories = _categorieService.GetAll(); var selectList = listOfCategories.Select(x =>new SelectListItem{Text = x.Name, Value = x.Id.ToString(), Selected = x.Id.Equals(blogToEdit.Category.Id)}).ToList(); selectList.Insert(0, new SelectListItem{Text = Messages.SelectAnItem, Value = Messages.SelectAnItem}); var viewModel = new BlogModel { BlogId = blogToEdit.Id, Active = blogToEdit.Actief, Content = blogToEdit.Text, Title = blogToEdit.Titel, Categories = selectList //at this point i see the expected item being selected //Categories = new IEnumerable<SelectListItem>(listOfCategories, "Id", "Naam", blogToEdit.CategorieId) }; return View(viewModel); } When i set a breakpoint just before the view is being returned, i see that the selectlist is filled as i expected. So at this point everything seems to be okay. The viewmodel is filled entirely correct. Then in my view (i'm using Razor) i've got the following two rules which are supposed to render the selectlist for me. @Html.LabelFor(m => m.Categories) @Html.DropDownListFor(model=>model.Categories, Model.Categories, Model.CategoryId) @Html.ValidationMessageFor(m => m.Categories) When I run the code and open the view to edit my blog, I can see all the correct data. Also the selectlist is rendered correctly, but the item i want to be selected lost it's selection. How can this be? Until the point the viewmodel is being returned with the view everything is okay. But when i view the webpage in the browser, the selectlist is there only with out the correct selection. What am I missing here? Or doing wrong?

    Read the article

  • selected value for dropdownbox in asp.net mvc using selectlist

    - by FosterZ
    hi, i have following selectlist for dropdownbox in aspnet mvc. This is the editEmployee Action controller, so while edit page is displayed i want to display a selectvalue in dropdownbox,since "SelectList" takes 3 parameters one for value,one for text and other is for selected value, here i'm not getting what should i pass in 3rd parameter, coz its asking an object for selected value. ViewData["DepartmentList"] = new SelectList(DepartmentRepository.GetDepartmentsBySchoolIdInList(ViewData["schoolId"].ToString()),"DepartmentId","DepartmentTitle"); here is the view =Html.DropDownList("DepartmentList")

    Read the article

  • Geting SelectList to MVC view using AJAX/jQuery

    - by Chris
    Hi all. I have a C# MVC application which is populating a dropdown based on a date selected. Once the date is selected I am sending it to an action via AJAX/jQuery. The action gets a list of items to return for that date. Here is where my problem is. I have done it previously where I render a partial view from the action and pass it the SelectList as the model. However, I really just want to do it inline in the original view, so I'm hoping there is some way I can return the SelectList and from there do some magic Javascript/JQuery to put it into a dropdown. Has anybody ever done this before? If so, what do I on the client end after calling the load() to return the SelectList? I've done something like this previously, when I was just returning a string or other value to be rendered as straight text: $("#returnTripRow").load("/Trip.aspx/GetTripsForGivenDate?date=" + escape(selection)); But I'm not sure how to intercept the data and morph it into am Html.DropDown() call, or equivalent. Any ideas? Thanks, Chris

    Read the article

  • ViewModel with SelectList binding in ASP.NET MVC2

    - by Junto
    I am trying to implement an Edit ViewModel for my Linq2SQL entity called Product. It has a foreign key linked to a list of brands. Currently I am populating the brand list via ViewData and using DropDownListFor, thus: <div class="editor-field"> <%= Html.DropDownListFor(model => model.BrandId, (SelectList)ViewData["Brands"])%> <%= Html.ValidationMessageFor(model => model.BrandId) %> </div> Now I want to refactor the view to use a strongly typed ViewModel and Html.EditorForModel(): <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <%=Html.EditorForModel() %> <p> <input type="submit" value="Save" /> </p> </fieldset> <% } %> In my Edit ViewModel, I have the following: public class EditProductViewModel { [HiddenInput] public int ProductId { get; set; } [Required()] [StringLength(200)] public string Name { get; set; } [Required()] [DataType(DataType.Html)] public string Description { get; set; } public IEnumerable<SelectListItem> Brands { get; set; } public int BrandId { get; set; } public EditProductViewModel(Product product, IEnumerable<SelectListItem> brands) { this.ProductId = product.ProductId; this.Name = product.Name; this.Description = product.Description; this.Brands = brands; this.BrandId = product.BrandId; } } The controller is setup like so: public ActionResult Edit(int id) { BrandRepository br = new BrandRepository(); Product p = _ProductRepository.Get(id); IEnumerable<SelectListItem> brands = br.GetAll().ToList().ToSelectListItems(p.BrandId); EditProductViewModel model = new EditProductViewModel(p, brands); return View("Edit", model); } The ProductId, Name and Description display correctly in the generated view, but the select list does not. The brand list definitely contains data. If I do the following in my view, the SelectList is visible: <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <%=Html.EditorForModel() %> <div class="editor-label"> <%= Html.LabelFor(model => model.BrandId) %> </div> <div class="editor-field"> <%= Html.DropDownListFor(model => model.BrandId, Model.Brands)%> <%= Html.ValidationMessageFor(model => model.BrandId) %> </div> <p> <input type="submit" value="Save" /> </p> </fieldset> <% } %> What am I doing wrong? Does EditorForModel() not generically support the SelectList? Am I missing some kind of DataAnnotation? I can't seem to find any examples of SelectList usage in ViewModels that help. I'm truly stumped. This answer seems to be close, but hasn't helped.

    Read the article

  • Using AJAX to return SelectList selected value

    - by Adventure
    At risk of asking the obvious... I need to use AJax.ActionLink to send the current value of a SelectList back to my controller. How do I do that? Below is part of my current View. I need to replace "15" with the current value of the SelectList. <% If Model.ShoppingListNames IsNot Nothing Then%> <%: Html.DropDownList("ShoppingListNames", Model.ShoppingListNames)%> <%: Ajax.ActionLink("Add to List", "AdjustMaterials", "Docs", New With {.userDocId = 15, .prodId = Model.ID, .quantity = 1}, New AjaxOptions With {.OnSuccess = "handleUpdate"})%> <% End If%>

    Read the article

  • There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'.

    - by Jimbo
    There are a couple of posts about this on Stack Overflow but none with an answer that seem to fix the problem in my current situation. I have a page with a table in it, each row has a number of text fields and a dropdown. All the dropdowns need to use the same SelectList data so I have set it up as follows: Controller ViewData["Submarkets"] = new SelectList(submarketRep.AllOrdered(), "id", "name"); View <%= Html.DropDownList("submarket_0", (SelectList)ViewData["Submarkets"], "(none)") %> I have used exactly this setup in many places, but for some reason in this particular view I get the error: There is no ViewData item of type 'IEnumerable' that has the key 'submarket_0'.

    Read the article

  • How does Model binding with a selectlist work?

    - by rsteckly
    Hi, I'm having problems retrieving the values of a selectlist in my form collection. I've tried making a viewmodel with an attribute with the same name as the select list. I'm honestly just realizing I REALLY don't understand how model binding works with selectlists. I've just been assuming that the following conventions apply: Name the select list the same thing as the attribute on the model you want it to bind to. Apart from that, I really don't get it. I've looked at several books on it and they're useless frankly. How does a select list work with a) form collection and b) a particular model?

    Read the article

  • How to code a C# Extension method to turn a Domain Model object into an Interface object?

    - by Dr. Zim
    When you have a domain object that needs to display as an interface control, like a drop down list, ifwdev suggested creating an extension method to add a .ToSelectList(). The originating object is a List of objects that have properties identical to the .Text and .Value properties of the drop down list. Basically, it's a List of SelectList objects, just not of the same class name. I imagine you could use reflection to turn the domain object into an interface object. Anyone have any suggestions for C# code that could do this? The SelectList is an MVC drop down list of SelectListItem. The idea of course is to do something like this in the view: <%= Html.DropDownList("City", (IEnumerable<SelectListItem>) ViewData["Cities"].ToSelectList() )

    Read the article

  • JQuery SelectList Option Changed doesn't refresh

    - by Jean-Philippe
    Hi. I have this select list: <select url="/Admin/SubCategories" name="TopParentId" id="ParentList"> <option value="">Please select a parent category</option> <option value="1" selected="selected">New Store</option> <option value="2">Extensions</option> <option value="3">Remodel</option> <option value="4">Bespoke Signage</option> <option value="5">Tactical Signage</option> <option value="6">Size Chart</option> <option value="7">Contact Info</option> </select> As you can see the option 1 is marked as selected. When I change the selection, I use this code to do an ajax call to get some values to populate a new select list: $("#ParentList").unbind("change"); $("#ParentList").change(function() { var itemId = $(this).val(); var url = $(this).attr("url"); var options; $.getJSON(url, itemId, function(data) { var defaultoption = '<option value="0">Please select a sub-category</option>'; options += defaultoption; $.each(data, function(index, optionData) { var option = '<option value="' + optionData.valueOf + '">' + optionData.Text + '</option>'; options += option; }); $("#SubParentList").html(options); }); }); My problem is that whenever I change the selection, the itemId is always the id of option 1, because it is marked as selected. It doesn't pick up the value of the option it is being changed too. Can someone please enlighten me of their knowledge. Regards, Jean-Philippe

    Read the article

  • ASP.Net MVC 3 Full Name In DropDownList

    - by tgriffiths
    I am getting a bit confused with this and need a little help please. I am developing a ASP.Net MVC 3 Web application using Entity Framework 4.1. I have a DropDownList on one of my Razor Views, and I wish to display a list of Full Names, for example Tom Jones Michael Jackson James Brown In my Controller I retrieve a List of User Objects, then select the FirstName and LastName of each User, and pass the data to a SelectList. List<User> Requesters = _userService.GetAllUsersByTypeIDOrgID(46, user.organisationID.Value).ToList(); var RequesterNames = from r in Requesters let person = new { UserID = r.userID, FullName = new { r.firstName, r.lastName } } orderby person.FullName ascending select person; viewModel.RequestersList = new SelectList(RequesterNames, "UserID", "FullName"); return View(viewModel); In my Razor View I have the following @Html.DropDownListFor(model => model.requesterID, Model.RequestersList, "Select", new { @class = "inpt_a"}) @Html.ValidationMessageFor(model => model.requesterID) However, when I run the code I get the following error At least one object must implement IComparable. I feel as if I am going about this the wrong way, so could someone please help with this? Thanks.

    Read the article

  • Filtering a select list via input box & jquery

    - by zSysop
    Hi all, I was wondering if i could get some help with filtering a select list using an input box via jquery. Here's what my js looks like, but it doesnt seem to work. I'm guessing this is because options within a select list are not hide-able. <script type="text/javascript"> $(document).ready(function() { $("#inputFilter").change(function() { var filter = $(this).val(); $("#selectList option").each(function() { var match = $(this).text().search(new RegExp(filter, "i")); if (match > 0) { $(this).show(); // Does not work } else $(this).hide(); }); }); }); </script> and here's my html <input id="inputFilter" /> <select id="selectList"> <option value="1111" text="1111 - London" /> <option value="1112" text="1111 - Paris" /> </select>

    Read the article

  • Set dropDownList to contain one value only, mvc3

    - by ParPar
    I have this in my controller: ViewBag.PriceListId = new SelectList(m_db.PriceLists, "Id", "Name", us.PriceListId); It contains two values now, but I want to enable the user to choose only the second value, and just if he does something else - allow him choose one of the both values. How do I omit the first value, and add and set him to default after that? Shoud I do it in my controller or use jquery? Thank in advance.

    Read the article

  • Drupal taxonomy multi-select default value

    - by msindle
    I'm using drupal 6.16 and have a set of taxonomy terms that are set up as a multi-select box. I would like for the first item to be selected when the user loads the page. I dont know if I need to add code to a file or just simply change a setting. I should warn you I do not have a lot of experience, but would rate myself as a low intermediate level programmer. Thanks in advance msindle

    Read the article

  • Change a select list display value upon selecting description

    - by eli
    Hello, I would like a select list that does the following: When the select list is open, display the list of descriptions. When the user selects an item, the select list will close an only the value will be displayed. The reason for this is to conserve space as the values will be much shorter. I'm hoping that there's an answer in jQuery. Thanks.

    Read the article

  • How can I restore the order of an (incomplete) select list to its original order?

    - by Rob
    I have two Select lists, between which you can move selected options. You can also move options up and down in the right list. When I move options back over to the left list, I would like them to retain their original position in the list order, even if the list is missing some original options. This is solely for the purpose of making the list more convenient for the user. I am currently defining an array with the original Select list onload. What would be the best way to implement this?

    Read the article

  • Selecting an item in an HTML SELECT list using keyboard doesnt trigger the CLICK event

    - by Jimbo
    I have an HTML select list which, when an item is selected, must show different information beneath it. The onclick or JQuery change events are triggered when a select list item is selected by being clicked on (mouse), but not when the user uses key presses (keyboard). Any idea what event to watch in order to determine when the selected list item has changed? Here is a BASIC test example: <select id="mylist" name="mylist"> <option value="">(none)</option> <option value="1">Test 1</option> <option value="2">Test 2</option> <option value="3">Test 3</option> </select> <span id="myspan"></span> <script type="text/javascript"> $("#mylist").change(function() { $("#myspan").html($("#mylist").attr("selectedIndex")); }); </script>

    Read the article

  • select list modified on-the-fly doesn't fire onChange() for new first element.

    - by staremperor
    In the code below, I'm using jquery 1.4.1 to modify the options in a select list when the user clicks on the list (replacing the single Old item with three New items). Selecting either New 2 or New 3 correctly fires the change() method (and show the alert), but selecting "New 1" does not. What am I missing? Thanks. <html> <head> <script type="text/javascript" src="js/jquery-1.4.1.min.js"></script> <script> $(document).ready(function() { $("#dropdown").mousedown(function() { $(this).empty(); $(this).append($("<option></option>").attr("value",100).text("New 1")); $(this).append($("<option></option>").attr("value",200).text("New 2")); $(this).append($("<option></option>").attr("value",300).text("New 3")); }); $("#dropdown").change(function() { alert($(this).val()); }); }); </script> <body> <select id="dropdown"><option value="1">Old 1</option></select>

    Read the article

  • load Javascript object from file

    - by megapool020
    Hi there, I asked a question in this thread Stackoverflow, and it works perfect. So tnx to all the users who gave me a reply. But now I have a other question. I would like to have the object in a seperate file, so I only need to update the file in stead of the JS file (otherwise it will be very big). I'm using JQUERY. I now looks like this (with all the info in the JS file). IBANInfo is used to fill a selectbox var IBANInfo = { "ccAL":{ countryCode:"AL", countryName:"Albani&euml;", IBANlength:"28", bankFormCode:"0 8n 0 ", accountNum:"0 16 0 " }, "ccAD":{ countryCode:"AD", countryName:"Andorra", IBANlength:"24", bankFormCode:"0 4n 4n", accountNum:"0 12 0 " }, "ccBE":{ countryCode:"BE", countryName:"Belgi&euml;", IBANlength:"16", bankFormCode:"0 3n 0 ", accountNum:"0 7n 2n" } }; //---- then this function is used to build the selectList function createSelect(){ var selectList = ''; var key; selectList += "<option value=''>Kies een land</option>\n"; for (key in IBANInfo) { if (IBANInfo.hasOwnProperty(key)) { var countryInfo = IBANInfo[key]; selectList += "<option value='"+countryInfo.countryCode+"'>"+countryInfo.countryName+"</option>\n"; } } $('#selectBox').html(selectList); } I thought I could do it like this, but I get the message undefined in my selectbox. var IBANInfo = $.get('include/countryCodes.txt'); // also tried var IBANInfo = $.getJSON('include/countryCodes.txt'); //---- then this function is used to build the selectList function createSelect(){ var selectList = ''; var key; selectList += "<option value=''>Kies een land</option>\n"; for (key in IBANInfo) { if (IBANInfo.hasOwnProperty(key)) { var countryInfo = IBANInfo[key]; selectList += "<option value='"+countryInfo.countryCode+"'>"+countryInfo.countryName+"</option>\n"; } } $('#selectBox').html(selectList); } /* the countryCodes.txt file is like this: { "ccAL":{ countryCode:"AL", countryName:"Albani&euml;", IBANlength:"28", bankFormCode:"0 8n 0 ", accountNum:"0 16 0 " }, "ccAD":{ countryCode:"AD", countryName:"Andorra", IBANlength:"24", bankFormCode:"0 4n 4n", accountNum:"0 12 0 " }, "ccBE":{ countryCode:"BE", countryName:"Belgi&euml;", IBANlength:"16", bankFormCode:"0 3n 0 ", accountNum:"0 7n 2n" } } */ What am I doing wrong. Tnx in advance

    Read the article

1 2 3 4 5 6  | Next Page >