Search Results

Search found 89 results on 4 pages for 'selectlistitem'.

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

  • Using LINQ Distinct: With an Example on ASP.NET MVC SelectListItem

    - by Joe Mayo
    One of the things that might be surprising in the LINQ Distinct standard query operator is that it doesn’t automatically work properly on custom classes. There are reasons for this, which I’ll explain shortly. The example I’ll use in this post focuses on pulling a unique list of names to load into a drop-down list. I’ll explain the sample application, show you typical first shot at Distinct, explain why it won’t work as you expect, and then demonstrate a solution to make Distinct work with any custom class. The technologies I’m using are  LINQ to Twitter, LINQ to Objects, Telerik Extensions for ASP.NET MVC, ASP.NET MVC 2, and Visual Studio 2010. The function of the example program is to show a list of people that I follow.  In Twitter API vernacular, these people are called “Friends”; though I’ve never met most of them in real life. This is part of the ubiquitous language of social networking, and Twitter in particular, so you’ll see my objects named accordingly. Where Distinct comes into play is because I want to have a drop-down list with the names of the friends appearing in the list. Some friends are quite verbose, which means I can’t just extract names from each tweet and populate the drop-down; otherwise, I would end up with many duplicate names. Therefore, Distinct is the appropriate operator to eliminate the extra entries from my friends who tend to be enthusiastic tweeters. The sample doesn’t do anything with the drop-down list and I leave that up to imagination for what it’s practical purpose could be; perhaps a filter for the list if I only want to see a certain person’s tweets or maybe a quick list that I plan to combine with a TextBox and Button to reply to a friend. When the program runs, you’ll need to authenticate with Twitter, because I’m using OAuth (DotNetOpenAuth), for authentication, and then you’ll see the drop-down list of names above the grid with the most recent tweets from friends. Here’s what the application looks like when it runs: As you can see, there is a drop-down list above the grid. The drop-down list is where most of the focus of this article will be. There is some description of the code before we talk about the Distinct operator, but we’ll get there soon. This is an ASP.NET MVC2 application, written with VS 2010. Here’s the View that produces this screen: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TwitterFriendsViewModel>" %> <%@ Import Namespace="DistinctSelectList.Models" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">     Home Page </asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">     <fieldset>         <legend>Twitter Friends</legend>         <div>             <%= Html.DropDownListFor(                     twendVM => twendVM.FriendNames,                     Model.FriendNames,                     "<All Friends>") %>         </div>         <div>             <% Html.Telerik().Grid<TweetViewModel>(Model.Tweets)                    .Name("TwitterFriendsGrid")                    .Columns(cols =>                     {                         cols.Template(col =>                             { %>                                 <img src="<%= col.ImageUrl %>"                                      alt="<%= col.ScreenName %>" />                         <% });                         cols.Bound(col => col.ScreenName);                         cols.Bound(col => col.Tweet);                     })                    .Render(); %>         </div>     </fieldset> </asp:Content> As shown above, the Grid is from Telerik’s Extensions for ASP.NET MVC. The first column is a template that renders the user’s Avatar from a URL provided by the Twitter query. Both the Grid and DropDownListFor display properties that are collections from a TwitterFriendsViewModel class, shown below: using System.Collections.Generic; using System.Web.Mvc; namespace DistinctSelectList.Models { /// /// For finding friend info on screen /// public class TwitterFriendsViewModel { /// /// Display names of friends in drop-down list /// public List FriendNames { get; set; } /// /// Display tweets in grid /// public List Tweets { get; set; } } } I created the TwitterFreindsViewModel. The two Lists are what the View consumes to populate the DropDownListFor and Grid. Notice that FriendNames is a List of SelectListItem, which is an MVC class. Another custom class I created is the TweetViewModel (the type of the Tweets List), shown below: namespace DistinctSelectList.Models { /// /// Info on friend tweets /// public class TweetViewModel { /// /// User's avatar /// public string ImageUrl { get; set; } /// /// User's Twitter name /// public string ScreenName { get; set; } /// /// Text containing user's tweet /// public string Tweet { get; set; } } } The initial Twitter query returns much more information than we need for our purposes and this a special class for displaying info in the View.  Now you know about the View and how it’s constructed. Let’s look at the controller next. The controller for this demo performs authentication, data retrieval, data manipulation, and view selection. I’ll skip the description of the authentication because it’s a normal part of using OAuth with LINQ to Twitter. Instead, we’ll drill down and focus on the Distinct operator. However, I’ll show you the entire controller, below,  so that you can see how it all fits together: using System.Linq; using System.Web.Mvc; using DistinctSelectList.Models; using LinqToTwitter; namespace DistinctSelectList.Controllers { [HandleError] public class HomeController : Controller { private MvcOAuthAuthorization auth; private TwitterContext twitterCtx; /// /// Display a list of friends current tweets /// /// public ActionResult Index() { auth = new MvcOAuthAuthorization(InMemoryTokenManager.Instance, InMemoryTokenManager.AccessToken); string accessToken = auth.CompleteAuthorize(); if (accessToken != null) { InMemoryTokenManager.AccessToken = accessToken; } if (auth.CachedCredentialsAvailable) { auth.SignOn(); } else { return auth.BeginAuthorize(); } twitterCtx = new TwitterContext(auth); var friendTweets = (from tweet in twitterCtx.Status where tweet.Type == StatusType.Friends select new TweetViewModel { ImageUrl = tweet.User.ProfileImageUrl, ScreenName = tweet.User.Identifier.ScreenName, Tweet = tweet.Text }) .ToList(); var friendNames = (from tweet in friendTweets select new SelectListItem { Text = tweet.ScreenName, Value = tweet.ScreenName }) .Distinct() .ToList(); var twendsVM = new TwitterFriendsViewModel { Tweets = friendTweets, FriendNames = friendNames }; return View(twendsVM); } public ActionResult About() { return View(); } } } The important part of the listing above are the LINQ to Twitter queries for friendTweets and friendNames. Both of these results are used in the subsequent population of the twendsVM instance that is passed to the view. Let’s dissect these two statements for clarification and focus on what is happening with Distinct. The query for friendTweets gets a list of the 20 most recent tweets (as specified by the Twitter API for friend queries) and performs a projection into the custom TweetViewModel class, repeated below for your convenience: var friendTweets = (from tweet in twitterCtx.Status where tweet.Type == StatusType.Friends select new TweetViewModel { ImageUrl = tweet.User.ProfileImageUrl, ScreenName = tweet.User.Identifier.ScreenName, Tweet = tweet.Text }) .ToList(); The LINQ to Twitter query above simplifies what we need to work with in the View and the reduces the amount of information we have to look at in subsequent queries. Given the friendTweets above, the next query performs another projection into an MVC SelectListItem, which is required for binding to the DropDownList.  This brings us to the focus of this blog post, writing a correct query that uses the Distinct operator. The query below uses LINQ to Objects, querying the friendTweets collection to get friendNames: var friendNames = (from tweet in friendTweets select new SelectListItem { Text = tweet.ScreenName, Value = tweet.ScreenName }) .Distinct() .ToList(); The above implementation of Distinct seems normal, but it is deceptively incorrect. After running the query above, by executing the application, you’ll notice that the drop-down list contains many duplicates.  This will send you back to the code scratching your head, but there’s a reason why this happens. To understand the problem, we must examine how Distinct works in LINQ to Objects. Distinct has two overloads: one without parameters, as shown above, and another that takes a parameter of type IEqualityComparer<T>.  In the case above, no parameters, Distinct will call EqualityComparer<T>.Default behind the scenes to make comparisons as it iterates through the list. You don’t have problems with the built-in types, such as string, int, DateTime, etc, because they all implement IEquatable<T>. However, many .NET Framework classes, such as SelectListItem, don’t implement IEquatable<T>. So, what happens is that EqualityComparer<T>.Default results in a call to Object.Equals, which performs reference equality on reference type objects.  You don’t have this problem with value types because the default implementation of Object.Equals is bitwise equality. However, most of your projections that use Distinct are on classes, just like the SelectListItem used in this demo application. So, the reason why Distinct didn’t produce the results we wanted was because we used a type that doesn’t define its own equality and Distinct used the default reference equality. This resulted in all objects being included in the results because they are all separate instances in memory with unique references. As you might have guessed, the solution to the problem is to use the second overload of Distinct that accepts an IEqualityComparer<T> instance. If you were projecting into your own custom type, you could make that type implement IEqualityComparer<T>, but SelectListItem belongs to the .NET Framework Class Library.  Therefore, the solution is to create a custom type to implement IEqualityComparer<T>, as in the SelectListItemComparer class, shown below: using System.Collections.Generic; using System.Web.Mvc; namespace DistinctSelectList.Models { public class SelectListItemComparer : EqualityComparer { public override bool Equals(SelectListItem x, SelectListItem y) { return x.Value.Equals(y.Value); } public override int GetHashCode(SelectListItem obj) { return obj.Value.GetHashCode(); } } } The SelectListItemComparer class above doesn’t implement IEqualityComparer<SelectListItem>, but rather derives from EqualityComparer<SelectListItem>. Microsoft recommends this approach for consistency with the behavior of generic collection classes. However, if your custom type already derives from a base class, go ahead and implement IEqualityComparer<T>, which will still work. EqualityComparer is an abstract class, that implements IEqualityComparer<T> with Equals and GetHashCode abstract methods. For the purposes of this application, the SelectListItem.Value property is sufficient to determine if two items are equal.   Since SelectListItem.Value is type string, the code delegates equality to the string class. The code also delegates the GetHashCode operation to the string class.You might have other criteria in your own object and would need to define what it means for your object to be equal. Now that we have an IEqualityComparer<SelectListItem>, let’s fix the problem. The code below modifies the query where we want distinct values: var friendNames = (from tweet in friendTweets select new SelectListItem { Text = tweet.ScreenName, Value = tweet.ScreenName }) .Distinct(new SelectListItemComparer()) .ToList(); Notice how the code above passes a new instance of SelectListItemComparer as the parameter to the Distinct operator. Now, when you run the application, the drop-down list will behave as you expect, showing only a unique set of names. In addition to Distinct, other LINQ Standard Query Operators have overloads that accept IEqualityComparer<T>’s, You can use the same techniques as shown here, with SelectListItemComparer, with those other operators as well. Now you know how to resolve problems with getting Distinct to work properly and also have a way to fix problems with other operators that require equality comparisons. @JoeMayo

    Read the article

  • DropDownList and SelectListItem Array Item Updates in MVC

    - by Rick Strahl
    So I ran into an interesting behavior today as I deployed my first MVC 4 app tonight. I have a list form that has a filter drop down that allows selection of categories. This list is static and rarely changes so rather than loading these items from the database each time I load the items once and then cache the actual SelectListItem[] array in a static property. However, when we put the site online tonight we immediately noticed that the drop down list was coming up with pre-set values that randomly changed. Didn't take me long to trace this back to the cached list of SelectListItem[]. Clearly the list was getting updated - apparently through the model binding process in the selection postback. To clarify the scenario here's the drop down list definition in the Razor View:@Html.DropDownListFor(mod => mod.QueryParameters.Category, Model.CategoryList, "All Categories") where Model.CategoryList gets set with:[HttpPost] [CompressContent] public ActionResult List(MessageListViewModel model) { InitializeViewModel(model); busEntry entryBus = new busEntry(); var entries = entryBus.GetEntryList(model.QueryParameters); model.Entries = entries; model.DisplayMode = ApplicationDisplayModes.Standard; model.CategoryList = AppUtils.GetCachedCategoryList(); return View(model); } The AppUtils.GetCachedCategoryList() method gets the cached list or loads the list on the first access. The code to load up the list is housed in a Web utility class. The method looks like this:/// <summary> /// Returns a static category list that is cached /// </summary> /// <returns></returns> public static SelectListItem[] GetCachedCategoryList() { if (_CategoryList != null) return _CategoryList; lock (_SyncLock) { if (_CategoryList != null) return _CategoryList; var catBus = new busCategory(); var categories = catBus.GetCategories().ToList(); // Turn list into a SelectItem list var catList= categories .Select(cat => new SelectListItem() { Text = cat.Name, Value = cat.Id.ToString() }) .ToList(); catList.Insert(0, new SelectListItem() { Value = ((int)SpecialCategories.AllCategoriesButRealEstate).ToString(), Text = "All Categories except Real Estate" }); catList.Insert(1, new SelectListItem() { Value = "-1", Text = "--------------------------------" }); _CategoryList = catList.ToArray(); } return _CategoryList; } private static SelectListItem[] _CategoryList ; This seemed normal enough to me - I've been doing stuff like this forever caching smallish lists in memory to avoid an extra trip to the database. This list is used in various places throughout the application - for the list display and also when adding new items and setting up for notifications etc.. Watch that ModelBinder! However, it turns out that this code is clearly causing a problem. It appears that the model binder on the [HttpPost] method is actually updating the list that's bound to and changing the actual entry item in the list and setting its selected value. If you look at the code above I'm not setting the SelectListItem.Selected value anywhere - the only place this value can get set is through ModelBinding. Sure enough when stepping through the code I see that when an item is selected the actual model - model.CategoryList[x].Selected - reflects that. This is bad on several levels: First it's obviously affecting the application behavior - nobody wants to see their drop down list values jump all over the place randomly. But it's also a problem because the array is getting updated by multiple ASP.NET threads which likely would lead to odd crashes from time to time. Not good! In retrospect the modelbinding behavior makes perfect sense. The actual items and the Selected property is the ModelBinder's way of keeping track of one or more selected values. So while I assumed the list to be read-only, the ModelBinder is actually updating it on a post back producing the rather surprising results. Totally missed this during testing and is another one of those little - "Did you know?" moments. So, is there a way around this? Yes but it's maybe not quite obvious. I can't change the behavior of the ModelBinder, but I can certainly change the way that the list is generated. Rather than returning the cached list, I can return a brand new cloned list from the cached items like this:/// <summary> /// Returns a static category list that is cached /// </summary> /// <returns></returns> public static SelectListItem[] GetCachedCategoryList() { if (_CategoryList != null) { // Have to create new instances via projection // to avoid ModelBinding updates to affect this // globally return _CategoryList .Select(cat => new SelectListItem() { Value = cat.Value, Text = cat.Text }) .ToArray(); } …}  The key is that newly created instances of SelectListItems are returned not just filtered instances of the original list. The key here is 'new instances' so that the ModelBinding updates do not update the actual static instance. The code above uses LINQ and a projection into new SelectListItem instances to create this array of fresh instances. And this code works correctly - no more cross-talk between users. Unfortunately this code is also less efficient - it has to reselect the items and uses extra memory for the new array. Knowing what I know now I probably would have not cached the list and just take the hit to read from the database. If there is even a possibility of thread clashes I'm very wary of creating code like this. But since the method already exists and handles this load in one place this fix was easy enough to put in. Live and learn. It's little things like this that can cause some interesting head scratchers sometimes…© Rick Strahl, West Wind Technologies, 2005-2012Posted in MVC  ASP.NET  .NET   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Creating a SelectListItem with the disabled="disabled" attribute

    - by Mark
    I realize Internet Explorer ignores the disabled attribute, but I'm not seeing a way to create, via the HtmlHelper, a SelectListItem that will spit out the following HTML: <option disabled="disabled">don't click this</option> The only properties SelectListItem has are: new SelectListItem{ Name = "don't click this", Value = string.Empty, Selected = false } The only option I see is to Subclass the SelectListItem to add an Enabled property to get the value to the view Not use the HTML helper for DropDownList Create a new HtmlHelper extension that accepts my new EnablableSelectList and adds my disabled attribute.

    Read the article

  • IEnumerable<SelectListItem> error question

    - by user281180
    I have the following code, but i`m having error of Error 6 foreach statement cannot operate on variables of type 'int' because 'int' does not contain a public definition for 'GetEnumerator' C:\Dev\DEV\Code\MvcUI\Models\MappingModel.cs 100 13 MvcUI How can I solve this? Note: string [] projectID; Class Employee { int id {get; set;} string Name {get;set;} } public IEnumerable<SelectListItem> GetStudents() { List<SelectListItem> result = new List<SelectListItem>(); foreach (var id in Convert.ToInt32(projectID)) { foreach( Employee emp in Project.Load(id)) result.Add(new SelectListItem { Selected = false, Text = emp.ID.ToString(), Value = emp.Name }); return result.AsEnumerable(); } }

    Read the article

  • How to map IEnumerable<SelectListItem> to IList<> for ListBox

    - by Superhuman
    I have two classes. Class1 and Class2. public class Class1{ ... public virtual IList<Class2> Class2s{get;set;} ... } public class Class2{ ... public virtual IList<Class1> Class1s{get;set;} ... } The view contains <%=Html.ListBox("Class2s", ViewData.Model.Class2s.Select( x => new SelectListItem { Text = x.Name, Value = x.Id.ToString(), Selected = ViewData.Model.Class1.Class2s.Any(y => y.Id == x.Id) }) They have many to many mapping. I have a ListBox in Class1 view which displays Class2. How to map the output of the ListBox back to IList Class2s property of Class1? I am able to display the values in the ListBox but unable to map back the SelectListItem to IList.

    Read the article

  • MVC's Html.DropDownList and "There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key '...'

    - by pjohnson
    ASP.NET MVC's HtmlHelper extension methods take out a lot of the HTML-by-hand drudgery to which MVC re-introduced us former WebForms programmers. Another thing to which MVC re-introduced us is poor documentation, after the excellent documentation for most of the rest of ASP.NET and the .NET Framework which I now realize I'd taken for granted. I'd come to regard using HtmlHelper methods instead of writing HTML by hand as a best practice. When I upgraded a project from MVC 3 to MVC 4, several hidden fields with boolean values broke, because MVC 3 called ToString() on those values implicitly, and MVC 4 threw an exception until you called ToString() explicitly. Fields that used HtmlHelper weren't affected. I then went through dozens of views and manually replaced hidden inputs that had been coded by hand with Html.Hidden calls. So for a dropdown list I was rendering on the initial page as empty, then populating via JavaScript after an AJAX call, I tried to use a HtmlHelper method: @Html.DropDownList("myDropdown") which threw an exception: System.InvalidOperationException: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'myDropdown'. That's funny--I made no indication I wanted to use ViewData. Why was it looking there? Just render an empty select list for me. When I populated the list with items, it worked, but I didn't want to do that: @Html.DropDownList("myDropdown", new List<SelectListItem>() { new SelectListItem() { Text = "", Value = "" } }) I removed this dummy item in JavaScript after the AJAX call, so this worked fine, but I shouldn't have to give it a list with a dummy item when what I really want is an empty select. A bit of research with JetBrains dotPeek (helpfully recommended by Scott Hanselman) revealed the problem. Html.DropDownList requires some sort of data to render or it throws an error. The documentation hints at this but doesn't make it very clear. Behind the scenes, it checks if you've provided the DropDownList method any data. If you haven't, it looks in ViewData. If it's not there, you get the exception above. In my case, the helper wasn't doing much for me anyway, so I reverted to writing the HTML by hand (I ain't scared), and amended my best practice: When an HTML control has an associated HtmlHelper method and you're populating that control with data on the initial view, use the HtmlHelper method instead of writing by hand.

    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

  • Easiest way to specify the selected option to a dropdown list in ASP.NET MVC

    - by sdr
    I have a list of options (IEnumerable< SelectListItem ) in my model that I want to use in multiple dropdowns in my view. But each of these dropdowns could have a different selected option. Is there an easy way to simply specfiy which should be selected if using the Html.DropDownList helper? At this point, the only way I can see is to generate the html myself and loop through the list of options like so: <% for(int i=0; i<10; i++) { %> <select name="myDropDown<%= i %>"> <% foreach(var option in Model.Options) { %> <option value="<%= Html.Encode(option.optValue) %>" <%if(ShouldBeSelected(i)) {%> selected="selected"<% } %>><%= Html.Encode(option.optText) %></option> <% } %> </select> <% } %>

    Read the article

  • Why does this render as a list of "System.Web.Mvc.SelectListItem"s?

    - by JMT
    I'm trying to populate a DropDownList with values pulled from a property, and my end result right now is a list of nothing but "System.Web.Mvc.SelectListItem"s. I'm sure there's some minor step I'm omitting here, but for the life of me I can't figure out what it is. The property GET generating the list: public IEnumerable<SelectListItem> AllFoo { get { var foo = from g in Bar orderby g.name select new SelectListItem { Value = g.fooid.ToString(), Text = g.name }; return foo.AsEnumerable(); } } The controller code: public ActionResult Edit(string id) { // n/a code ViewData["fooList"] = new SelectList(g.AllFoo, g.fooid); return View(model); } The view code: <%= Html.DropDownListFor(model => model.fooid, ViewData["fooList"] as SelectList) %>

    Read the article

  • The ViewData item that has the key 'MY KEY' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'.

    - by JBibbs
    I am trying to populate a dropdown list from a database mapped with Linq 2 SQL, using ASP.NET MVC 2, and keep getting this error. I am so confused because I am declaring a variable with the type IEnumerable<SelectListItem> on the second line, but the error makes me think this is not the case. I feel like this should be very simple, but I am struggling. Any help is appreciated. Here are the interesting bits of my controller: public ActionResult Create() { var db = new DB(); IEnumerable<SelectListItem> basetypes = db.Basetypes.Select(b => new SelectListItem { Value = b.basetype, Text = b.basetype }); ViewData["basetype"] = basetypes; return View(); } And here are the interesting bits of my view: <div class="editor-label"> <%: Html.LabelFor(model => model.basetype) %> </div> <div class="editor-field"> <%: Html.DropDownList("basetype") %> <%: Html.ValidationMessageFor(model => model.basetype) %> </div> Here is the Post action when submitting the Form // POST: /Meals/Create [HttpPost] public ActionResult Create(Meal meal) { if (ModelState.IsValid) { try { // TODO: Add insert logic here var db = new DB(); db.Meals.InsertOnSubmit(meal); db.SubmitChanges(); return RedirectToAction("Index"); } catch { return View(meal); } } else { return View(meal); } } Thanks.

    Read the article

  • Html.DropDownListFor not behaving as expected ASP.net MVC

    - by rybl
    Hello, I am new to ASP.net MVC and I am having trouble getting dropdown lists to work correctly. I have a strongly typed view that is attempting to use a Html.DropDownListFor as follows: <%=Html.DropDownListFor(Function(model) model.Arrdep, Model.ArrdepOptions)%> I am populating the list with a property in my model as follows: Public ReadOnly Property ArrdepOptions() As List(Of SelectListItem) Get Dim list As New List(Of SelectListItem) Dim arriveListItem As New SelectListItem() Dim departListItem As New SelectListItem() arriveListItem.Text = "Arrive At" arriveListItem.Value = ArriveDepart.Arrive departListItem.Text = "Depart At" departListItem.Value = ArriveDepart.Depart Select Case Me.Arrdep Case ArriveDepart.Arrive : arriveListItem.Selected = True Case Else : departListItem.Selected = True End Select list.Add(departListItem) list.Add(arriveListItem) Return list End Get End Property The Select Case works find and it sets the right SelectListItem as Selected, but when my view renders the dropdown list no matter what is marked as selected the generated HTML does not have anything selected. Am I obviously doing something wrong or missing something, but I can't for the life of me figure out what.

    Read the article

  • Linq to Sql, Repositories, and Asp.Net MVC ViewData: How to remove redundancy?

    - by Dr. Zim
    Linq to SQL creates objects which are IQueryable and full of relations. Html Helpers require specific interface objects like IEnumerable<SelectListItem>. What I think could happen: Reuse the objects from Linq to SQL without all the baggage, i.e., return Pocos from the Linq to SQL objects without additional Domain Model classes? Extract objects that easily convert to (or are) Html helper objects like the SelectListItem enumeration? Is there any way to do this without breaking separation of concerns? Some neat oop trick to bridge the needs? For example, if this were within a repository, the SelectListItem wouldn't be there. The select new is a nice way to cut out an object from the Linq to SQL without the baggage but it's still referencing a class that shouldn't be referenced: IEnumerable<SelectListItem> result = (from record in db.table select new SelectListItem { Selected = record.selected, Text= record.Text, Value= record.Value } ).AsEnumerable();

    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

  • Predicate problem in ToSelectList

    - by Stefanvds
    the ToSelectList method I have: public static IList<SelectListItem> ToSelectList<T>(this IEnumerable<T> itemsToMap, Func<T, string> textProperty, Func<T, string> valueProperty, Predicate<T> isSelected) { var result = new List<SelectListItem>(); foreach (var item in itemsToMap) { result.Add(new SelectListItem { Value = valueProperty(item), Text = textProperty(item), Selected = isSelected(item) }); } return result; } when I call this method here: public static List<SelectListItem> lesgeverList(int selectedID) { NASDataContext _db = new NASDataContext(); var lesg = (from l in _db.Lesgevers where l.LG_Naam != "leeg" orderby l.LG_Naam select l).ToSelectList(m => m.LG_Naam + " " + m.LG_Vnaam, m => m.LG_ID.ToString(), m => m.LG_ID == selectedID); return lesg.ToList(); } the selectlist I get has the selectedID as selected. now, when I want to have multiple selected items, I give a list of Lesgevers public static List<SelectListItem> lesgeverList(List<Lesgever> lg) { NASDataContext _db = new NASDataContext(); var test = (from l in _db.Lesgevers where l.LG_Naam != "leeg" && lg.Contains(l) orderby l.LG_Naam, l.LG_Vnaam select l).ToList(); var lesg = (from l in _db.Lesgevers where l.LG_Naam != "leeg" orderby l.LG_Naam, l.LG_Vnaam select l).ToSelectList(m => m.LG_Naam + " " + m.LG_Vnaam, m => m.LG_ID.ToString(), m => lg.Contains(m)); return lesg.ToList(); } the var test does return the Lesgevers that i have in the lg List, in my 'var lesg', there are no selectlistitem's selected at all. where is my mistake? :) how do I fix thix?

    Read the article

  • Inheritance issue

    - by VenkateshGudipati
    hi Friends i am facing a issue in Inheritance i have a interface called Irewhizz interface irewhzz { void object save(object obj); void object getdata(object obj); } i write definition in different class like public user:irewhzz { public object save(object obj); { ....... } public object getdata(object obj); { ....... } } this is antoher class public client:irewhzz { public object save(object obj); { ....... } public object getdata(object obj); { ....... } } now i have different classes like public partial class RwUser { #region variables IRewhizzDataHelper irewhizz; IRewhizzRelationDataHelper irewhizzrelation; private string _firstName; private string _lastName; private string _middleName; private string _email; private string _website; private int _addressId; private string _city; private string _zipcode; private string _phone; private string _fax; //private string _location; private string _aboutMe; private string _username; private string _password; private string _securityQuestion; private string _securityQAnswer; private Guid _user_Id; private long _rwuserid; private byte[] _image; private bool _changepassword; private string _mobilephone; private int _role; #endregion //IRewhizz is the interface and its functions are implimented by UserDataHelper class //RwUser Class is inheriting the UserDataHelper Properties and functions. //Here UserDataHelper functions are called with Irewhizz Interface Object but not with the //UserDataHelper class Object It will resolves the unit testing conflict. #region Constructors public RwUser() : this(new UserDataHelper(), new RewhizzRelationalDataHelper()) { } public RwUser(IRewhizzDataHelper repositary, IRewhizzRelationDataHelper relationrepositary) { irewhizz = repositary; irewhizzrelation = relationrepositary; } #endregion #region Properties public int Role { get { return _role; } set { _role = value; } } public string MobilePhone { get { return _mobilephone; } set { _mobilephone = value; } } public bool ChangePassword { get { return _changepassword; } set { _changepassword = value; } } public byte[] Image { get { return _image; } set { _image = value; } } public string FirstName { get { return _firstName; } set { _firstName = value; } } public string LastName { get { return _lastName; } set { _lastName = value; } } public string MiddleName { get { return _middleName; } set { _middleName = value; } } public string Email { get { return _email; } set { _email = value; } } public string Website { get { return _website; } set { _website = value; } } public int AddressId { get { return _addressId; } set { _addressId = value; } } public string City { get { return _city; } set { _city = value; } } public string Zipcode { get { return _zipcode; } set { _zipcode = value; } } public string Phone { get { return _phone; } set { _phone = value; } } public string Fax { get { return _fax; } set { _fax = value; } } //public string Location //{ // get // { // return _location; // } // set // { // _location = value; // } //} public string AboutMe { get { return _aboutMe; } set { _aboutMe = value; } } public string username { get { return _username; } set { _username = value; } } public string password { get { return _password; } set { _password = value; } } public string SecurityQuestion { get { return _securityQuestion; } set { _securityQuestion = value; } } public string SecurityQAnswer { get { return _securityQAnswer; } set { _securityQAnswer = value; } } public Guid UserID { get { return _user_Id; } set { _user_Id = value; } } public long RwUserID { get { return _rwuserid; } set { _rwuserid = value; } } #endregion #region MemberFunctions // DataHelperDataContext db = new DataHelperDataContext(); // RewhizzDataHelper rwdh=new RewhizzDataHelper(); //It saves user information entered by user and returns the id of that user public object saveUserInfo(RwUser userObj) { userObj.UserID = irewhizzrelation.GetUserId(username); var res = irewhizz.saveData(userObj); return res; } //It returns the security questions for user registration } public class Agent : RwUser { IRewhizzDataHelper irewhizz; IRewhizzRelationDataHelper irewhizzrelation; private int _roleid; private int _speclisationid; private int[] _language; private string _brokaragecompany; private int _loctionType_lk; private string _rolename; private int[] _specialization; private string _agentID; private string _expDate; private string _regstates; private string _selLangs; private string _selSpels; private string _locations; public string Locations { get { return _locations; } set { _locations = value; } } public string SelectedLanguages { get { return _selLangs; } set { _selLangs = value; } } public string SelectedSpecialization { get { return _selSpels; } set { _selSpels = value; } } public string RegisteredStates { get { return _regstates; } set { _regstates = value; } } //private string _registeredStates; public string AgentID { get { return _agentID; } set { _agentID = value; } } public string ExpDate { get { return _expDate; } set { _expDate = value; } } private int[] _registeredStates; public SelectList RegisterStates { set; get; } public SelectList Languages { set; get; } public SelectList Specializations { set; get; } public int[] RegisterdStates { get { return _registeredStates; } set { _registeredStates = value; } } //public string RegisterdStates //{ // get // { // return _registeredStates; // } // set // { // _registeredStates = value; // } //} public int RoleId { get { return _roleid; } set { _roleid = value; } } public int SpeclisationId { get { return _speclisationid; } set { _speclisationid = value; } } public int[] Language { get { return _language; } set { _language = value; } } public int LocationTypeId { get { return _loctionType_lk; } set { _loctionType_lk = value; } } public string BrokarageCompany { get { return _brokaragecompany; } set { _brokaragecompany = value; } } public string Rolename { get { return _rolename; } set { _rolename = value; } } public int[] Specialization { get { return _specialization; } set { _specialization = value; } } public Agent() : this(new AgentDataHelper(), new RewhizzRelationalDataHelper()) { } public Agent(IRewhizzDataHelper repositary, IRewhizzRelationDataHelper relationrepositary) { irewhizz = repositary; irewhizzrelation = relationrepositary; } public void inviteclient() { //Code related to mailing } //DataHelperDataContext dataObj = new DataHelperDataContext(); //#region IRewhizzFactory Members //public List<object> getAgentInfo(string username) //{ // var res=dataObj.GetCompleteUserDetails(username); // return res.ToList(); // throw new NotImplementedException(); //} //public List<object> GetRegisterAgentData(string username) //{ // var res= dataObj.RegisteredUserdetails(username); // return res.ToList(); //} //public void saveAgentInfo(string username, string password, string firstname, string lastname, string middlename, string securityquestion, string securityQanswer) //{ // User userobj=new User(); // var result = dataObj.rw_Users_InsertUserInfo(firstname, middlename, lastname, dataObj.GetUserId(username), securityquestion, securityquestionanswer); // throw new NotImplementedException(); //} //#endregion public Agent updateData(Agent objectId) { objectId.UserID = irewhizzrelation.GetUserId(objectId.username); objectId = (Agent)irewhizz.updateData(objectId); return objectId; } public Agent GetAgentData(Agent agentodj) { agentodj.UserID = irewhizzrelation.GetUserId(agentodj.username); agentodj = (Agent)irewhizz.getData(agentodj); if (agentodj.RoleId != 0) agentodj.Rolename = (string)(string)irewhizzrelation.getValue(agentodj.RoleId); if (agentodj.RegisterdStates.Count() != 0) { List<SelectListItem> list = new List<SelectListItem>(); string regstates = ""; foreach (int i in agentodj.RegisterdStates) { SelectListItem listitem = new SelectListItem(); listitem.Value = i.ToString(); listitem.Text = (string)irewhizzrelation.getValue(i); list.Add(listitem); regstates += (string)irewhizzrelation.getValue(i) + ","; } SelectList selectlist = new SelectList(list, "Value", "Text"); agentodj.RegisterStates = selectlist; if(regstates!=null) agentodj.RegisteredStates = regstates.Remove(regstates.Length - 1); } if (agentodj.Language.Count() != 0) { List<SelectListItem> list = new List<SelectListItem>(); string selectedlang = ""; foreach (int i in agentodj.Language) { SelectListItem listitem = new SelectListItem(); listitem.Value = i.ToString(); listitem.Text = (string)irewhizzrelation.getValue(i); list.Add(listitem); selectedlang += (string)irewhizzrelation.getValue(i) + ","; } SelectList selectlist = new SelectList(list, "Value", "Text"); agentodj.Languages = selectlist; // agentodj.SelectedLanguages = selectedlang; } if (agentodj.Specialization.Count() != 0) { List<SelectListItem> list = new List<SelectListItem>(); string selectedspel = ""; foreach (int i in agentodj.Specialization) { SelectListItem listitem = new SelectListItem(); listitem.Value = i.ToString(); listitem.Text = (string)irewhizzrelation.getValue(i); list.Add(listitem); selectedspel += (string)irewhizzrelation.getValue(i) + ","; } SelectList selectlist = new SelectList(list, "Value", "Text"); agentodj.Specializations = selectlist; //agentodj.SelectedSpecialization = selectedspel; } return agentodj; } public void SaveImage(byte[] pic, String username) { irewhizzrelation.SaveImage(pic, username); } } now the issue is when ever i am calling agent class it is given error like null reference exception for rwuser class can any body give the solution thanks in advance

    Read the article

  • Defining a select list through controller and view model

    - by Ibrar Hussain
    I have a View Model that looks like this: public class SomeViewModel { public SomeViewModel(IEnumerable<SelectListItem> orderTemplatesListItems) { OrderTemplateListItems = orderTemplatesListItems; } public IEnumerable<SelectListItem> OrderTemplateListItems { get; set; } } I then have an Action in my Controller that does this: public ActionResult Index() { var items = _repository.GetTemplates(); var selectList = items.Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() }).ToList(); var viewModel = new SomeViewModel { OrderTemplateListItems = selectList }; return View(viewModel); } Lastly my view: @Html.DropDownListFor(n => n.OrderTemplateListItems, new SelectList(Model.OrderTemplateListItems, "value", "text"), "Please select an order template") The code works fine and my select list populates wonderfully. Next thing I need to do is set the selected value that will come from a Session["orderTemplateId"] which is set when the user selects a particular option from the list. Now after looking online the fourth parameter should allow me to set a selected value, so if I do this: @Html.DropDownListFor(n => n.OrderTemplateListItems, new SelectList(Model.OrderTemplateListItems, "value", "text", 56), "Please select an order template") 56 is the Id of the item that I want selected, but to no avail. I then thought why not do it in the Controller? As a final attempt I tried building up my select list items in my Controller and then passing the items into the View: public ActionResult Index() { var items = _repository.GetTemplates(); var orderTemplatesList = new List<SelectListItem>(); foreach (var item in items) { if (Session["orderTemplateId"] != null) { if (item.Id.ToString() == Session["orderTemplateId"].ToString()) { orderTemplatesList.Add(new SelectListItem { Text = item.Name, Value = item.Id.ToString(), Selected = true }); } else { orderTemplatesList.Add(new SelectListItem { Text = item.Name, Value = item.Id.ToString() }); } } else { orderTemplatesList.Add(new SelectListItem { Text = item.Name, Value = item.Id.ToString() }); } } var viewModel = new SomeViewModel { OrderTemplateListItems = orderTemplatesList }; return View(viewModel); } Leaving my View like so: @Html.DropDownListFor(n => n.OrderTemplateListItems, new SelectList(Model.OrderTemplateListItems, "value", "text"), "Please select an order template") Nothing! Why isn't this working for me?

    Read the article

  • ASP.NET MVC 2 DropDownList not rendering

    - by Tomaszewski
    Hi, so I don't understand what I am doing wrong here. I want to populate a DropDownList inside the master page of my ASP.NET MVC 2 app. Projects.Master <div id="supaDiv" class="mainNav"> <% Html.DropDownList("navigationList"); %> </div> MasterController.cs namespace ProjectsPageMVC.Controllers.Abstracts { public abstract class MasterController : Controller { public MasterController() { List<SelectListItem> naviList = new List<SelectListItem>(); naviList.Add(new SelectListItem { Selected = true, Text = "AdvanceWeb", Value = "http://4168web/advanceweb/" }); naviList.Add(new SelectListItem { Selected = false, Text = " :: AdvanceWeb Admin", Value = "http://4168web/advanceweb/admin/admindefault.aspx" }); ViewData["navigationList"] = naviList; } } } ProjectsController namespace ProjectsPageMVC.Controllers { public class ProjectsController : MasterController { public ActionResult Index() { return View(); } } } The DropDownList is not even showing up in the DOM and I am at a loss as to what I am doing wrong.

    Read the article

  • MVC2 html dropdownlist is invisible

    - by Deb
    I am just trying to populate a html.dropdown list using mvc2 in VS2008. But the control is not displayed at all. Here is my code public ActionResult Index() { ViewData["Time"] = DateTime.Now.ToString(); var mdl = new List<SelectListItem>(); mdl.Add(new SelectListItem { Value = "1", Text = "Module One" }); mdl.Add(new SelectListItem { Value = "2", Text = "Module Two" }); ViewData["moduleList"] = new SelectList(mdl,"Value", "Text"); return View("MainMenu"); } and here is the markup <div> <%Html.DropDownList("moduleList", (IEnumerable<SelectListItem>)ViewData["moduleList"]); %> </div> Where did i go wrong ?

    Read the article

  • Why doesn't the default model binder update my partial view model on postback?

    - by bdnewbe
    I have a class that contains another class as one of its properties. public class SiteProperties { public SiteProperties() { DropFontFamily = "Arial, Helvetica, Sans-serif"; } public string DropFontFamily { get; set; } private ResultPageProperties m_ResultPagePropertyList; public ResultPageProperties ResultPagePropertyList { get { if (m_ResultPagePropertyList == null) m_ResultPagePropertyList = new ResultPageProperties(); return m_ResultPagePropertyList; } set { m_ResultPagePropertyList = value; } } } The second class has just one property public class ResultPageProperties { public ResultPageProperties() { ResultFontFamily = "Arial, Helvetica, Sans-serif"; } public string ResultFontFamily { get; set; } } My controller just grabs the SiteProperties and returns the view. On submit, it accepts SiteProperties and returns the same view. public class CompanyController : Controller { public ActionResult SiteOptions(int id) { SiteProperties site = new SiteProperties(); PopulateProperyDropDownLists(); return View("SiteOptions", site); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult SiteOptions(SiteProperties properties) { PopulateProperyDropDownLists(); return View("SiteOptions", properties); } private void PopulateProperyDropDownLists() { var fontFamilyList = new List<SelectListItem>(); fontFamilyList.Add(new SelectListItem() { Text = "Arial, Helvetica, Sans-serif", Value = "Arial, Helvetica, Sans-serif" }); fontFamilyList.Add(new SelectListItem() { Text = "Times New Roman, Times, serif", Value = "Times New Roman, Times, serif" }); fontFamilyList.Add(new SelectListItem() { Text = "Courier New, Courier, Monospace", Value = "Courier New, Courier, Monospace" }); ViewData["FontFamilyList"] = fontFamilyList; } } The view contains a partial view that renders the ResultPageProperties Model. <% using (Html.BeginForm("SiteOptions", "Company", FormMethod.Post)) {%> <p><input type="submit" value="Submit" /></p> <div>View level input</div> <div> <label>Font family</label><br /> <%= Html.DropDownListFor(m => m.DropFontFamily, ViewData["FontFamilyList"] as List<SelectListItem>, new { Class = "UpdatesDropDownExample" })%> </div> <% Html.RenderPartial("ResultPagePropertyInput", Model.ResultPagePropertyList); %> <% } %> The partial is just <div style='margin-top: 1em;'>View level input</div> <div> <label>Font family</label><br /> <%= Html.DropDownListFor(m => m.ResultFontFamily, ViewData["FontFamilyList"] as List<SelectListItem>, new { Class = "UpdatesResultPageExample" })%> </div> OK, so when the page renders, you get "Arial, ..." in both selects. If you choose another option for both and click submit, the binder populates the SiteProperties object and passes it to the controller. However, the ResultFontFamily always contains the original value. I was expecting it to have the value the user selected. What am I missing?

    Read the article

  • How to bind Lists of a custom view model to a dropDownList an get the selected value after POST in A

    - by user187220
    I have following problem. In my view model I defined some list properties as follows: public class BasketAndOrderSearchCriteriaViewModel { List<KeyValuePair> currencies; public ICollection<KeyValuePair> Currencies { get { if (this.currencies == null) this.currencies = new List<KeyValuePair>(); return this.currencies; } } List<KeyValuePair> deliverMethods; public ICollection<KeyValuePair> DeliveryMethods { get { if (this.deliverMethods == null) this.deliverMethods = new List<KeyValuePair>(); return this.deliverMethods; } } } This view model is embedded in another view model: public class BasketAndOrderSearchViewModel { public BasketAndOrderSearchCriteriaViewModel Criteria { [System.Diagnostics.DebuggerStepThrough] get { return this.criteria; } } } I use 2 action methods; one is for the GET and the other for POST: [HttpGet] public ActionResult Search(BasketAndOrderSearchViewModel model){...} [HttpPost] public ActionResult SubmitSearch(BasketAndOrderSearchViewModel model){...} In the view I implement the whole view model by using the EditorFor-Html Helper which does not want to automatically display DropDownLists for List properties! 1. Question: How can you let EditorFor display DropDownLists? Since I could not figure out how to display DropDownLists by using EditorFor, I used the DropDownList Html helper and filled it through the view model as follows: public IEnumerable<SelectListItem> DeliveryMethodAsSelectListItem() { List<SelectListItem> list = new List<SelectListItem>(); list.Add(new SelectListItem() { Selected = true, Text = "<Choose Delivery method>", Value = "0" }); foreach (var item in this.DeliveryMethods) { list.Add(new SelectListItem() { Selected = false, Text = item.Value, Value = item.Key }); } return list; } My 2. question: As you can see I pass my view model to the action metho with POST attribute! Is there a way to get the selected value of a DropDownList get binded to the passed view model? At the moment all the DropDownList are empty and the selected value can only be fetched by the Request.Form which I definitely want to avoid! I would greatly appreciate some ideas or tips on this!

    Read the article

  • ASP.Net MVC2 DropDownListFor

    - by hermiod
    Hi all I am trying to learn MVC2, C# and Linq to Entities all in one project (yes, I am mad) and I am experiencing some problems with DropDownListFor and passing the SelectList to it. This is the code in my controller: public ActionResult Create() { var Methods = te.Methods.Select(a => a); List<SelectListItem> MethodList = new List<SelectListItem>(); foreach (Method me in Methods) { SelectListItem sli=new SelectListItem(); sli.Text = me.Description; sli.Value = me.method_id.ToString(); MethodList.Add(sli); } ViewData["MethodList"] = MethodList.AsEnumerable(); Talkback tb = new Talkback(); return View(tb); } and I am having troubles trying to get the DropDownListFor to take the MethodList in ViewData. When I try: <%:Html.DropDownListFor(model => model.method_id,new SelectList("MethodList","method_id","Description",Model.method_id)) %> It errors out with the following message DataBinding: 'System.Char' does not contain a property with the name 'method_id'. I know why this is, as it is taking MethodList as a string, but I can't figure out how to get it to take the SelectList. If I do the following with a normal DropDownList: <%: Html.DropDownList("MethodList") %> It is quite happy with this. Can anyone help?

    Read the article

  • How to retrieve value from DropDownListFor html helper in ASP>NET MVC2?

    - by Eedoh
    Hello I know there was few similar questions here about DropDownListFor, but neither helped me... I use Entity Framework as ORM in my project. There's EF model called "Stete". Stete has Foreign on EF model called "Drustva" Now I'm trying to make a form for editing the data, for Stete model. I managed to display everything, including Stete.Drustva.Naziv property, but I can't get this last property in my handler method [HttpPost]. It always return 0, no matter what I select in drop down list. Here's the code: DrustvaController: public static IEnumerable<SelectListItem> DrustvaToSelectListItemsById(this KnjigaStetnikaEntities pEntities, int Id) { IEnumerable<Drustva> drustva = (from d in pEntities.Drustva select d).ToList(); return drustva.OrderBy(drustvo => drustvo.Naziv).Select(drustvo => new SelectListItem { Text = drustvo.Naziv, Value = drustvo.Id.ToString(), Selected = (drustvo.Id == Id)? true : false }); } SteteController: private IEnumerable<SelectListItem> privremenaListaDrustava(int Id) { using (var ctx = new KnjigaStetnikaEntities()) { return ctx.DrustvaToSelectListItemsById(Id); } } public ActionResult IzmijeniPodatkeStete(Int32 pBrojStete) { PretragaStetaModel psm = new PretragaStetaModel(); ViewData["drustva"] = privremenaListaDrustava(psm.VratiStetuPoBrojuStete(pBrojStete).Drustva.Id); ViewData.Model = new Models.Stete(); return View("EditView", (Stete.Models.Stete)psm.GetSteta(pBrojStete)); } EditView: <div class="editor-label"> <%: Html.Label("Društvo") %> </div> <div class="editor-field"> <%: Html.DropDownListFor(m => m.Drustva.Naziv, ViewData["drustva"] as IEnumerable<SelectListItem>) %> <%: Html.ValidationMessageFor(model => model.FKDrustvo) %> </div> I am sorry for not translating names of the objects into english, but they hardly have appropriate translation. If necessary, I can try creating similar example...

    Read the article

  • How to retrieve value from DropDownListFor html helper in ASP.NET MVC2?

    - by Eedoh
    Hello I know there was few similar questions here about DropDownListFor, but neither helped me... I use Entity Framework as ORM in my project. There's EF model called "Stete". Stete has Foreign on EF model called "Drustva" Now I'm trying to make a form for editing the data, for Stete model. I managed to display everything, including Stete.Drustva.Naziv property, but I can't get this last property in my handler method [HttpPost]. It always return 0, no matter what I select in drop down list. Here's the code: DrustvaController: public static IEnumerable<SelectListItem> DrustvaToSelectListItemsById(this KnjigaStetnikaEntities pEntities, int Id) { IEnumerable<Drustva> drustva = (from d in pEntities.Drustva select d).ToList(); return drustva.OrderBy(drustvo => drustvo.Naziv).Select(drustvo => new SelectListItem { Text = drustvo.Naziv, Value = drustvo.Id.ToString(), Selected = (drustvo.Id == Id)? true : false }); } SteteController: private IEnumerable<SelectListItem> privremenaListaDrustava(int Id) { using (var ctx = new KnjigaStetnikaEntities()) { return ctx.DrustvaToSelectListItemsById(Id); } } public ActionResult IzmijeniPodatkeStete(Int32 pBrojStete) { PretragaStetaModel psm = new PretragaStetaModel(); ViewData["drustva"] = privremenaListaDrustava(psm.VratiStetuPoBrojuStete(pBrojStete).Drustva.Id); ViewData.Model = new Models.Stete(); return View("EditView", (Stete.Models.Stete)psm.GetSteta(pBrojStete)); } EditView: <div class="editor-label"> <%: Html.Label("Društvo") %> </div> <div class="editor-field"> <%: Html.DropDownListFor(m => m.Drustva.Naziv, ViewData["drustva"] as IEnumerable<SelectListItem>) %> <%: Html.ValidationMessageFor(model => model.FKDrustvo) %> </div> I am sorry for not translating names of the objects into english, but they hardly have appropriate translation. If necessary, I can try creating similar example...

    Read the article

  • How to add validation errors in the validation collection asp.net mvc?

    - by johndoe
    Inside my controller's action I have the following code: public ActionResult GridAction(string id) { if (String.IsNullOrEmpty(id)) { // add errors to the errors collection and then return the view saying that you cannot select the dropdownlist value with the "Please Select" option } return View(); UPDATE: if (String.IsNullOrEmpty(id)) { // add error ModelState.AddModelError("GridActionDropDownList", "Please select an option"); return RedirectToAction("Orders"); } } UPDATE 2: Here is my updated code: @Html.DropDownListFor(x => x.SelectedGridAction, Model.GridActions,"Please Select") @Html.ValidationMessageFor(x => x.SelectedGridAction) The Model looks like the following: public class MyInvoicesViewModel { private List<SelectListItem> _gridActions; public int CurrentGridAction { get; set; } [Required(ErrorMessage = "Please select an option")] public string SelectedGridAction { get; set; } public List<SelectListItem> GridActions { get { _gridActions = new List<SelectListItem>(); _gridActions.Add(new SelectListItem() { Text = "Export to Excel", Value = "1"}); return _gridActions; } } } And here is my controller action: public ActionResult GridAction(string id) { if (String.IsNullOrEmpty(id)) { // add error ModelState.AddModelError("SelectedGridAction", "Please select an option"); return RedirectToAction("Orders"); } return View(); } Nothing happens! I am totally lost on this one! UPDATE 3: I am now using the following code but still the validation is not firing: public ActionResult GridAction(string id) { var myViewModel= new MyViewModel(); myViewModel.SelectedGridAction = id; // id is passed as null if (!ModelState.IsValid) { return View("Orders"); }

    Read the article

  • Cascading DropDown List in MVC 4

    - by Misi
    I have a ASP.NET MVC 4 project with EF I have a table with Parteners. This table has 2 types of parteners : agents(part_type=1) and clients(part_type=2). In an Create view I have the first DropDownList that shows all my agents, a button and the second DDL that shows all my clients that correspond to the selected agent. Q1 : What button shoud I use ? , , @Html.ActionLink() ? Create.cshtml <div class="editor-field"> @Html.DropDownList("idagenti", ViewData["idagenti"] as List<SelectListItem>, String.Empty) </div> @*a button*@ <div class="editor-label"> @Html.LabelFor(model => model.id_parten, "Client") </div> <div class="editor-field"> @Html.DropDownList("id_parten", String.Empty) @Html.ValidationMessageFor(model => model.id_parten) </div> OrdersController.cs public ActionResult Create(int? id) // id is the selected agent { var agqry = db.partener.Where(p => p.part_type == 1).Where(p => p.activ == true); var cltqry = db.partener.Where(p => p.part_type == 2).Where(p => p.activ == true); List<SelectListItem> idagenti = new List<SelectListItem>(); foreach (partener ag in agqry) { idagenti.Add(new SelectListItem { Text = ag.den_parten, Value = ag.id_parten.ToString() }); } if (id != null) { cltqry = cltqry.Where(p => p.par_parten == id); } ViewData["idagenti"] = idagenti; ViewBag.id_parten = new SelectList(cltqry, "id_parten", "den_parten");// } Q: How can I pass the selected agent id from the first DDL to my controller ?

    Read the article

1 2 3 4  | Next Page >