Search Results

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

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

  • LINQ Guid toString()

    - by Sevki
    Hi this seems like it should work, from something in collectionofsomestuff select new SelectListItem(){Text = Name, Value = SomeGuid.ToString(), Selected = false}; When I try to do this it doesn't work give me error LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression. Is there a workaround?

    Read the article

  • Get selected value of dropdownlist in asp.net MVC

    - by Xulfee
    how can i get select value of dropdownlist and here is my code which is working fine. var list = new[] { new Person { Id = 1, Name = "Name1" }, new Person { Id = 2, Name = "Name2" }, new Person { Id = 3, Name = "Name3" } }; var selectList = new SelectList(list, "Id", "Name", 2); ViewData["People"] = selectList; <%= Html.DropDownListFor(model => model.Peoples, ViewData["People"] as IEnumerable<SelectListItem>)%>

    Read the article

  • asp.net mvc binding to listbox

    - by ruben
    Hi im having trouble displaying data in a mcv website, i end up with selectlistitem displayed on the listbox as opposed to the id or value of the object that i am binding in my controller I do this Authors = new SelectList(_authorRepository.GetAll(), "authorId", "Firstname",null), and im my View <%= Html.ListBox("AuthorsList", new SelectList(Model.Authors))% what else am I missing?

    Read the article

  • ASP.net MVC DropLownList db.SaveChanges not saving selection

    - by WMIF
    I have looked through a ton of tutorials and suggestions on how to work with DropDownList in MVC. I was able to get most of it working, but the selected item is not saving into the database. I am using MVC 3 and Razor for the view. My DropDownList is getting created with the correct values and good looking HTML. When I set a breakpoint, I can see the correct selected item ID in the model getting sent to controller. When the view goes back to the index, the DropDownList value is not set. The other values save just fine. Here are the related views. The DropDownList is displaying a list of ColorModel names as text with the ID as the value. public class ItemModel { [Key] public int ItemID { get; set; } public string Name { get; set; } public string Description { get; set; } public virtual ColorModel Color { get; set; } } public class ItemEditViewModel { public int ItemID { get; set; } public string Name { get; set; } public string Description { get; set; } public int ColorID { get; set; } public IEnumerable<SelectListItem> Colors { get; set; } } public class ColorModel { [Key] public int ColorID { get; set; } public string Name { get; set; } public virtual IList<ItemModel> Items { get; set; } } Here are the controller actions. public ActionResult Edit(int id) { ItemModel itemmodel = db.Items.Find(id); ItemEditViewModel itemEditModel; itemEditModel = new ItemEditViewModel(); itemEditModel.ItemID = itemmodel.ItemID; if (itemmodel.Color != null) { itemEditModel.ColorID = itemmodel.Color.ColorID; } itemEditModel.Description = itemmodel.Description; itemEditModel.Name = itemmodel.Name; itemEditModel.Colors = db.Colors .ToList() .Select(x => new SelectListItem { Text = x.Name, Value = x.ColorID.ToString() }); return View(itemEditModel); } [HttpPost] public ActionResult Edit(ItemEditViewModel itemEditModel) { if (ModelState.IsValid) { ItemModel itemmodel; itemmodel = new ItemModel(); itemmodel.ItemID = itemEditModel.ItemID; itemmodel.Color = db.Colors.Find(itemEditModel.ColorID); itemmodel.Description = itemEditModel.Description; itemmodel.Name = itemEditModel.Name; db.Entry(itemmodel).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(itemEditModel); } The view has this for the DropDownList, and the others are just EditorFor(). @Html.DropDownListFor(model => model.ColorID, Model.Colors, "Select a Color") When I set the breakpoint on the db.Color.Find(...) line, I show this in the Locals window for itemmodel.Color: {System.Data.Entity.DynamicProxies.ColorModel_0EB80C07207CA5D88E1A745B3B1293D3142FE2E644A1A5202B90E5D2DAF7C2BB} When I expand that line, I can see the ColorID that I chose from the dropdown box, but it does not save into the database.

    Read the article

  • Knockout with ASP.Net MVC2 - HTML Extension Helpers for input controls

    - by Renso
    Goal: Defining Knockout-style input controls can be tedious and also may be something that you may find obtrusive, mixing your HTML with data bind syntax as well as binding your aspx, ascx files to Knockout. The goal is to make specifying Knockout specific HTML tags easy, seamless really, as well as being able to remove references to Knockout easily. Environment considerations: ASP.Net MVC2 or later Knockoutjs.js How to:     public static class HtmlExtensions     {         public static string DataBoundCheckBox(this HtmlHelper helper, string name, bool isChecked, object htmlAttributes)         {             var builder = new TagBuilder("input");             var dic = new RouteValueDictionary(htmlAttributes) { { "data-bind", String.Format("checked: {0}", name) } };             builder.MergeAttributes(dic);             builder.MergeAttribute("type", @"checkbox");             builder.MergeAttribute("name", name);             builder.MergeAttribute("value", @"true");             if (isChecked)             {                 builder.MergeAttribute("checked", @"checked");             }             return builder.ToString(TagRenderMode.SelfClosing);         }         public static MvcHtmlString DataBoundSelectList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, String optionLabel)         {             var attrProperties = new StringBuilder();             attrProperties.Append(String.Format("optionsText: '{0}'", name));             if (!String.IsNullOrEmpty(optionLabel)) attrProperties.Append(String.Format(", optionsCaption: '{0}'", optionLabel));             attrProperties.Append(String.Format(", value: {0}", name));             var dic = new RouteValueDictionary { { "data-bind", attrProperties.ToString() } };             return helper.DropDownList(name, selectList, optionLabel, dic);         }         public static MvcHtmlString DataBoundSelectList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, String optionLabel, object htmlAttributes)         {             var attrProperties = new StringBuilder();             attrProperties.Append(String.Format("optionsText: '{0}'", name));             if (!String.IsNullOrEmpty(optionLabel)) attrProperties.Append(String.Format(", optionsCaption: '{0}'", optionLabel));             attrProperties.Append(String.Format(", value: {0}", name));             var dic = new RouteValueDictionary(htmlAttributes) {{"data-bind", attrProperties}};             return helper.DropDownList(name, selectList, optionLabel, dic);         }         public static String DataBoundSelectList(this HtmlHelper helper, String options, String optionsText, String value)         {             return String.Format("<select data-bind=\"options: {0},optionsText: '{1}',value: {2}\"></select>", options, optionsText, value);         }         public static MvcHtmlString DataBoundTextBox(this HtmlHelper helper, string name, object value, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", name));             return helper.TextBox(name, value, dic);         }         public static MvcHtmlString DataBoundTextBox(this HtmlHelper helper, string name, string observable, object value, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", observable));             return helper.TextBox(name, value, dic);         }         public static MvcHtmlString DataBoundTextArea(this HtmlHelper helper, string name, string value, int rows, int columns, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", name));             return helper.TextArea(name, value, rows, columns, dic);         }         public static MvcHtmlString DataBoundTextArea(this HtmlHelper helper, string name, string observable, string value, int rows, int columns, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", observable));             return helper.TextArea(name, value, rows, columns, dic);         }         public static string BuildUrlFromExpression<T>(this HtmlHelper helper, Expression<Action<T>> action)         {             var values = CreateRouteValuesFromExpression(action);             var virtualPath = helper.RouteCollection.GetVirtualPath(helper.ViewContext.RequestContext, values);             if (virtualPath != null)             {                 return virtualPath.VirtualPath;             }             return null;         }         public static string ActionLink<T>(this HtmlHelper helper, Expression<Action<T>> action, string linkText)         {             return helper.ActionLink(action, linkText, null);         }         public static string ActionLink<T>(this HtmlHelper helper, Expression<Action<T>> action, string linkText, object htmlAttributes)         {             var values = CreateRouteValuesFromExpression(action);             var controllerName = (string)values["controller"];             var actionName = (string)values["action"];             values.Remove("controller");             values.Remove("action");             return helper.ActionLink(linkText, actionName, controllerName, values, new RouteValueDictionary(htmlAttributes)).ToHtmlString();         }         public static MvcForm Form<T>(this HtmlHelper helper, Expression<Action<T>> action)         {             return helper.Form(action, FormMethod.Post);         }         public static MvcForm Form<T>(this HtmlHelper helper, Expression<Action<T>> action, FormMethod method)         {             var values = CreateRouteValuesFromExpression(action);             string controllerName = (string)values["controller"];             string actionName = (string)values["action"];             values.Remove("controller");             values.Remove("action");             return helper.BeginForm(actionName, controllerName, values, method);         }         public static MvcForm Form<T>(this HtmlHelper helper, Expression<Action<T>> action, FormMethod method, object htmlAttributes)         {             var values = CreateRouteValuesFromExpression(action);             string controllerName = (string)values["controller"];             string actionName = (string)values["action"];             values.Remove("controller");             values.Remove("action");             return helper.BeginForm(actionName, controllerName, values, method, new RouteValueDictionary(htmlAttributes));         }         public static string VertCheckBox(this HtmlHelper helper, string name, bool isChecked)         {             return helper.CustomCheckBox(name, isChecked, null);         }          public static string CustomCheckBox(this HtmlHelper helper, string name, bool isChecked, object htmlAttributes)         {             TagBuilder builder = new TagBuilder("input");             builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));             builder.MergeAttribute("type", "checkbox");             builder.MergeAttribute("name", name);             builder.MergeAttribute("value", "true");             if (isChecked)             {                 builder.MergeAttribute("checked", "checked");             }             return builder.ToString(TagRenderMode.SelfClosing);         }         public static string Script(this HtmlHelper helper, string script, object scriptAttributes)         {             var pathForCRMScripts = ScriptsController.GetPathForCRMScripts();             if (ScriptOptimizerConfig.EnableMinimizedFileLoad)             {                 string newPathForCRM = pathForCRMScripts + "Min/";                 ScriptsController.ServerPathMapper = new ServerPathMapper();                 string fullPath = ScriptsController.ServerMapPath(newPathForCRM);                 if (!File.Exists(fullPath + script))                     return null;                 if (!Directory.Exists(fullPath))                     return null;                 pathForCRMScripts = newPathForCRM;             }             var builder = new TagBuilder("script");             builder.MergeAttributes(new RouteValueDictionary(scriptAttributes));             builder.MergeAttribute("type", @"text/javascript");             builder.MergeAttribute("src", String.Format("{0}{1}", pathForCRMScripts.Replace("~", String.Empty), script));             return builder.ToString(TagRenderMode.SelfClosing);         }         private static RouteValueDictionary CreateRouteValuesFromExpression<T>(Expression<Action<T>> action)         {             if (action == null)                 throw new InvalidOperationException("Action must be provided");             var body = action.Body as MethodCallExpression;             if (body == null)             {                 throw new InvalidOperationException("Expression must be a method call");             }             if (body.Object != action.Parameters[0])             {                 throw new InvalidOperationException("Method call must target lambda argument");             }             // This will build up a RouteValueDictionary containing the controller name, action name, and any             // parameters passed as part of the "action" parameter.             string name = body.Method.Name;             string controllerName = typeof(T).Name;             if (controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))             {                 controllerName = controllerName.Remove(controllerName.Length - 10, 10);             }             var values = BuildParameterValuesFromExpression(body) ?? new RouteValueDictionary();             values.Add("controller", controllerName);             values.Add("action", name);             return values;         }         private static RouteValueDictionary BuildParameterValuesFromExpression(MethodCallExpression call)         {             // Build up a RouteValueDictionary containing parameter names as keys and parameter values             // as values based on the MethodCallExpression passed in.             var values = new RouteValueDictionary();             ParameterInfo[] parameters = call.Method.GetParameters();             // If the passed in method has no parameters, just return an empty dictionary.             if (parameters.Length == 0)             {                 return values;             }             for (int i = 0; i < parameters.Length; i++)             {                 object parameterValue;                 Expression expression = call.Arguments[i];                 // If the current parameter is a constant, just use its value as the parameter value.                 var constant = expression as ConstantExpression;                 if (constant != null)                 {                     parameterValue = constant.Value;                 }                 else                 {                     // Otherwise, compile and execute the expression and use that as the parameter value.                     var function = Expression.Lambda<Func<object>>(Expression.Convert(expression, typeof(object)),                                                                    new ParameterExpression[0]);                     try                     {                         parameterValue = function.Compile()();                     }                     catch                     {                         parameterValue = null;                     }                 }                 values.Add(parameters[i].Name, parameterValue);             }             return values;         }     }   Some observations: The first two DataBoundSelectList overloaded methods are specifically built to load the data right into the drop down box as part of the HTML response stream rather than let Knockout's engine populate the options client-side. The third overloaded method does it client-side via the viewmodel. The first two overloads can be done when you have no requirement to add complex JSON objects to your lists. Furthermore, why render and parse the JSON object when you can have it all built and rendered server-side like any other list control.

    Read the article

  • MVC Dropdown List isn't binding to the model.

    - by Rod McLeay
    Hi, I am trying set up a simple dropdown list but I dont seem to be able to get it to bind to the Model. I am using Asp.Net MVC and nhibernate. My dropdown list is declared like so: <%= Html.DropDownListFor(model => model.Project, (IEnumerable<SelectListItem>)ViewData["Projects"], " -- Select -- ", new { name = "Project" })%> I set up the select list like so: ViewData["Projects"] = new SelectList(projectRepository.GetAll(), "EntityGUID", "Name", editEntity.Project); This seems to bind the select list to the Dropdown fine, but the SelectedValue is not set. it shows up as the default --- Select --- Also when I save this data, the dropdown does not bind to the model, I have to manually set the object like so to save it: entity.Project = projectRepository.GetById(new Guid(Request["Project"].ToString())); I believe I have take the correct messures to have this item bind directly to my model. Is there something I am missing here? Many thanks for your time, Rod

    Read the article

  • DropDownListFor does not select value if using int[] as value

    - by Iceman
    In my view <%= Html.DropDownListFor( x => x.Countries[ i ], x.CountryList )%> in my controller public int[ ] Countries { get; set; } public List<SelectListItem> CountryList { get; set; } When the forms gets posted there is no problem, the dropdown is populated and the values the user selects are posted. But when I try to load the form with already assigned values to the Countries[ ] it does not get selected.

    Read the article

  • MVC2 Binding isn't working for Html.DropDownListFor<>

    - by devlife
    I'm trying to use the Html.DropDownListFor< HtmlHelper and am having a little trouble binding on post. The HTML renders properly but I never get a "selected" value when submitting. <%= Html.DropDownListFor( m => m.TimeZones, Model.TimeZones, new { @class = "SecureDropDown", name = "SelectedTimeZone" } ) %> [Bind(Exclude = "TimeZones")] public class SettingsViewModel : ProfileBaseModel { public IEnumerable TimeZones { get; set; } public string TimeZone { get; set; } public SettingsViewModel() { TimeZones = GetTimeZones(); TimeZone = string.Empty; } private static IEnumerable GetTimeZones() { var timeZones = TimeZoneInfo.GetSystemTimeZones().ToList(); return timeZones.Select( t = new SelectListItem { Text = t.DisplayName, Value = t.Id } ); } } I've tried a few different things and am sure I am doing something stupid... just not sure what it is :)

    Read the article

  • jquery ui autocomplete is changing my listbox

    - by oo
    I am trying to change my comboboxes to use autocomplete so i leverage the code listed here (which worked perfectly for my dropdowns) The issue is that i also on the same page have a listbox with the following code: <%= Html.ListBox("Cars", Model.BodyParts.Select( x => new SelectListItem { Text = x.Name, Value = x.Id, Selected = Model.CarsSelected.Any(y => y.Id == x.Id) } ))%> and it appears that the jquery ui code is changing this to a autocomplete dropdown as well (as opposed to keeping it as a multi select list box) any idea how to prevent this from happening?

    Read the article

  • Switching from LinqToXYZ to LinqToObjects

    - by spender
    In answering this question, it got me thinking... I often use this pattern: collectionofsomestuff //here it's LinqToEntities .Select(something=>new{something.Name,something.SomeGuid}) .ToArray() //From here on it's LinqToObjects .Select(s=>new SelectListItem() { Text = s.Name, Value = s.SomeGuid.ToString(), Selected = false }) Perhaps I'd split it over a couple of lines, but essentially, at the ToArray point, I'm effectively enumerating my query and storing the resulting sequence so that I can further process it with all the goodness of a full CLR to hand. As I have no interest in any kind of manipulation of the intermediate list, I use ToArray over ToList as there's less overhead. I do this all the time, but I wonder if there is a better pattern for this kind of problem?

    Read the article

  • ASP.NET MVC Populating a DropDownList with a value from the view

    - by lomaxx
    In my controller I have this: ViewData["maskList"] = new SelectList(equipmentRepository.GetMasks(), "Id", "DisplayName"); and then I bind it to my view using <div each="var nfa in mfa.NasalFittingAssessment"> ${Html.DropDownList("NasalMaskTypeId", ViewData["maskList"] as IEnumerable<System.Web.Mvc.SelectListItem>, new { class = "ddl" })} </div> Note that I'm using the spark view engine so this DropDownList is getting rendered to the page via a loop. This means that the selected value of the dropdown list will change on each iteration of the loop. What I can't work out is how to pass in the value I want to set the DropDownList to based on the value that is currently being rendered to the screen.

    Read the article

  • Problem with ASP.NET MVC DropDownList not displaying selected value

    - by Jova
    I have an aspx page which allows me to edit articles. Among things I can edit is which category the article belongs to. The category is chosen through a DropDownList as shown here, <%= Html.DropDownList("categoryID", (IEnumerable<SelectListItem>)ViewData["CategoryID"], new { @class = "textbox" }) %> However, the articles category isn't selected when I go to that page. The ViewData I use for the DropDownList looks like this, ViewData["CategoryID"] = new SelectList(categories, "CategoryID", "Title", article.CategoryID); Which should select the article.CategoryID as it's selected value. Have I done this wrong?

    Read the article

  • Adding global blank option to DroDownList in MVC

    - by Diegos Grace
    Is there a way of using a templated helper in mvc so that each and every select list in my project has a custom default 'Choose an option' with null value etc. The posts I have seen seem a little complex, is it possible to have a DropDownList.ascx file in shared view folder with something like this: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<SelectListItem>>" %> <%= Html.DropDownList(selectlist name, selectlist value, "Choose an option")%> And then having a UIHint("DropDownList") for each dropdownlist in the ViewModel? Some guidance on syntax of parameters would be much appreciated, where name and value of the viewmodel dropdownlist plus the 'Choose an option' string are passed. Or is this all wishful thinking?

    Read the article

  • Access parent class from custom attribute

    - by madcapnmckay
    Hi, Is it possible to access a parent class from within an attribute. For example I would like to create a DropDownListAttribute which can be applied to a property of a viewmodel class in MVC and then create a drop down list from an editor template. I am following a similar line as Kazi Manzur Rashid here. He adds the collection of categories into viewdata and retrieves them using the key supplied to the attribute. I would like to do something like the below, public ExampleDropDownViewModel { public IEnumerable<SelectListItem> Categories {get;set;} [DropDownList("Categories")] public int CategoryID { get;set; } } The attribute takes the name of the property containing the collection to bind to. I can't figure out how to access a property on the parent class of the attribute. Does anyone know how to do this? Thanks

    Read the article

  • How to save checkbox checked values in Database

    - by user1298215
    How to save checkbox values in database. Below is my view code. @foreach (var item in Model) { @Html.CheckBox("statecheck", (IEnumerable<SelectListItem>)ViewData["StatesList"]) @Html.DisplayFor(modelItem => item.state_name) </br> } <input class="ASPbutton" type="submit" value="submit"/> Below is My controller. public ActionResult States() { ViewData["StatesList"] = new SelectList(am.FindUpcomingStates().ToList(), "state_id", "state_Name"); return View(); } My model is public IQueryable<state> FindUpcomingStates() { return from state in Adm.states orderby state.state_name select state; } After clicking submit button checked item state_id will be saved into database. I wrote like below in Controller, but i got true or false values, i want state_id [AcceptVerbs(HttpVerbs.Post)] public ActionResult States(string _stateName, char[] statecheck, FormCollection formvalues) { statecheck = Request.Form["statecheck"].ToArray(); ViewData["StatesList"] = new SelectList(am.FindUpcomingStates222().ToList(), "state_id", "state_id", _stateName); }

    Read the article

  • Using Where method in Linq 2 Entities with OR clause.

    - by Dani
    I want to use Where method in Linq 2 entities that will be equal to this userRepository.Users.Where(u=>u.RoleID == 1 || u=>u.RoldID == 2).Select(o => new SelectListItem { Text = o.Role.RoleName, Value = o.RoleID.ToString() }).ToList(); The problem of course is in Where(u=u.RoleID == 1 || u=u.RoldID == 2) The problem is that I don't know how to use WHERE method with OR inside the WHERE clause. any ideas (the code above will not compile of-course b/c of the lambda expression. userRepository.Users returns an list of Users entities. I guess that and can be done using concatenation of .Where().Where() but I need an OR.

    Read the article

  • How can I get a property as an Entity in Action of Asp.Net Mvc ?

    - by Felipe
    Hi all, i'd like to know how can I get a property like an entity, for example: My Model: public class Product { public int Id { get; set; } public string Name { get; set; } public Category Category { get; set; } } View: Name: <%=Html.TextBoxFor(x => x.Name) %> Category: <%= Html.DropDownList("Category", IEnumerable<SelectListItem>)ViewData["Categories"]) %> Controller: public ActionResult Save(Product product) { /// produtct.Category ??? } and how is the category property ? It's fill by the view ? ASP.Net MVC know how to fill this object by ID ? Thanks!

    Read the article

  • asp.net mvc xval validation

    - by mctayl
    Hi there I am using xval for the first time, it seems to work fine for required fields, However I am having some issues first of all it does not seem to validate booleans and also client validation is not working for me, this is not a major issue for me, the one that I really need to work is the stringlength property. It seems to do something because the form is not posted when the string length is exceeded, however no error message is displayed to the user which is obviously not what I want, has anyone been able to do this successfully? My model goes like this using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace PitchPortal.Core { public class DocumentMetadata { //[Required] // public bool visibility { get; set; } [Required,StringLength(10, ErrorMessage = "title is too long")] public string title { get; set; } [Required, StringLength(10, ErrorMessage = "description is too long")] public string description { get; set; } [Required, StringLength(10, ErrorMessage = "summary is too long")] public string summary { get; set; } } } the html goes like this <div id="results" title="Upload results"/> <form id="myForm" action="<%=Url.Action("New") %>" method="post" enctype="multipart/form-data"> <% Html.EnableClientValidation(); %> <%= Html.ValidationSummary() %> <table> <tr> <td> <%=Html.Label("File")%></td> <td> <input type="file" id="file1" name="fileUpload" /> <br /> <%=Html.SubmitButton<DocumentController>(x => x.Upload(), "GetImage", "")%> </td> <td> <%=Html.ValidationMessage("file1")%> </td> </tr> <tr> <td> <%=Html.Label("Visible")%></td> <td> <%= Html.RadioButton( "visibility",true,true) %>true <%= Html.RadioButton("visibility", false)%>false </td> <td> <%= Html.ValidationMessage("visibility")%> </td> </tr> <tr> <td> <%=Html.Label("Title")%></td> <td> <%=Html.TextBox("doc.title")%></td> <td> <%= Html.ValidationMessage("doc.title")%></td> </tr> <tr> <td> <%=Html.Label("Description")%></td> <td><%= Html.TextArea("doc.description")%></td> <td><%= Html.ValidationMessage("doc.description")%></td> </tr> <tr> <td> <%=Html.Label("Summary")%></td> <td> <%= Html.TextArea("doc.summary")%></td> <td> <%= Html.ValidationMessage("doc.summary")%></td> </tr> <tr> <td> <%=Html.Label("Filetype")%></td> <td> <%= Html.DropDownList("Filetype_id", (IEnumerable<SelectListItem>)ViewData.Model.AllFiletypesList)%> </td> <td> <%= Html.ValidationMessage("doc.Filetype_id")%> </td> </tr> <tr> <td> <%=Html.Label("Category")%></td> <td><%= Html.DropDownList("cat.parent_id", (IEnumerable<SelectListItem>)ViewData.Model.AllCategoriesList, "-please select item-", new { className = "unselected" })%> </td> <td><%= Html.ValidationMessage("cat.parent_id")%> </td> </tr> <% if (Session["TempFolder"] == null) { for (int i = 1; i < 6; i++) { %> <tr> <td> <%=Html.Label("Shot "+i.ToString()) %> </td> <td><input type="file" id="image_<%= i.ToString() %>" name="image_<%= i.ToString() %>" /></td> </tr> <% } }%> <tr> <td><input type="submit" value="save"/></td> </tr> </table> </form> </div>

    Read the article

  • Mapping and metadata information could not be found for EntityType Exception

    - by dcompiled
    I am trying out ASP.NET MVC Framework 2 with the Microsoft Entity Framework and when I try and save new records I get this error: Mapping and metadata information could not be found for EntityType 'WebUI.Controllers.PersonViewModel' My Entity Framework container stores records of type Person and my view is strongly typed with class PersonViewModel which derives from Person. Records would save properly until I tried to use the derived view model class. Can anyone explain why the metadata class doesnt work when I derive my view model? I want to be able to use a strongly typed model and also use data annotations (metadata) without resorting to mixing my storage logic (EF classes) and presentation logic (views). // Rest of the Person class is autogenerated by the EF [MetadataType(typeof(Person.Metadata))] public partial class Person { public sealed class Metadata { [DisplayName("First Name")] [Required(ErrorMessage = "Field [First Name] is required")] public object FirstName { get; set; } [DisplayName("Middle Name")] public object MiddleName { get; set; } [DisplayName("Last Name")] [Required(ErrorMessage = "Field [Last Name] is required")] public object LastName { get; set; } } } // From the View (PersonCreate.aspx) <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<WebUI.Controllers.PersonViewModel>" %> // From PersonController.cs public class PersonViewModel : Person { public List<SelectListItem> TitleList { get; set; } } // end class PersonViewModel

    Read the article

  • kendo ui filtering the grid table, need some idea

    - by cool_spirit
    I want to filter the table by last name, but cant work, here is my code in controller public JsonResult Filtering() { HealthContext rc = new HealthContext(); var last = rc.Profiles.Select(lastt => new SelectListItem { Text = lastt.LastName, Value = lastt.Id.ToString() }).ToList(); return Json(last.ToList(), JsonRequestBehavior.AllowGet); } in view <script type="text/x-kendo-template" id="template"> <div class="toolbar"> <label class="category-label" for="Last name"> by last name:</label> <input type="search" id="LastName" style="width: 230px"></input> </div> </script> and also <script> $(document).ready(function() { $("#grid").kendoGrid({ dataSource: { transport: { read: { url: "/Profiles/GetJsonData", dataType: "json" } }, pageSize: 10, }, toolbar: kendo.template($("#template").html()), height: 250, filterable: true, sortable: true, pageable: true, defaultSorting: 'LastName ASC', columns: [{ field: "Id", filterable: false }, { field: "FirstName", title: "First Name", width: 100, }, { field: "LastName", title: "Last Name", width: 200 }, { field: "Gender", title: "Gender" } ] }); var dropDown = grid.find("#LastName").kendoDropDownList({ dataTextField: "LastName", dataValueField: "Id", autoBind: false, optionLabel: "All", dataSource: { severFiltering: true, transport: { read: { url: "/Profiles/Filtering", dataType: "json" } }, }, change: function() { var value = this.value(); if (value) { grid.data("kendoGrid").dataSource.filter({ field: "Id", operator: "eq", value: parseInt(value) }); } else { grid.data("kendoGrid").dataSource.filter({}); } } }); }); </script> so the problem is the drop down list is not show up as well as the value/ data, any idea guys?

    Read the article

  • ASP.Net MVC Object Reference in Edit View when using DropDownListFor()

    - by hermiod
    This question is related to another I ask recently, it can be found here for some background information. Here is the code in the Edit ActionResult: public virtual ActionResult Edit(int id) { ///Set data for DropDownLists. ViewData["MethodList"] = tr.ListMethods(); ViewData["GenderList"] = tr.ListGenders(); ViewData["FocusAreaList"] = tr.ListFocusAreas(); ViewData["SiteList"] = tr.ListSites(); ViewData["TypeList"] = tr.ListTalkbackTypes(); ViewData["CategoryList"] = tr.ListCategories(); return View(tr.GetTalkback(id)); } I add lists to the ViewData to use in the dropdownlists, these are all IEnumerable and are all returning values. GetTalkback() returns an Entity framework object of type Talkback which is generated from the Talkback table. The DropDownListFor code is: <%: Html.DropDownListFor(model=>model.method_id,new SelectList(ViewData["MethodList"] as IEnumerable<SelectListItem>,"Value","Text",Model.method_id)) %> The record I am viewing has values in all fields. When I click submit on the View, I get an Object reference not set to an instance of an object. error on the above line. There are a number of standard fields in the form prior to this, so the error is only occurring on dropdown lists, and it is occurring on all of them. Any ideas? This is my first foray in to MVC, C#, and Entity so I am completely lost!

    Read the article

  • In My MVC Controller, Can I Add a Value to My HTML.DropDownList?

    - by Aaron Salazar
    In my view I have an HTML DropDownList that is filled, in my controller, using a List<string>. <%= Html.DropDownList("ReportedIssue", (IEnumerable<SelectListItem>)ViewData["ReportedIssue"]) %> List<string> reportedIssue = new List<string>(); reportedIssue.Add("All"); reportedIssue.Add(...); ViewData["ReportedIssue"] = new SelectList(reportedIssue); In my view the result is: <select name="ReportedIssue" id="ReportedIssue"><option>All</option> <option>All</option> <option>...</option> </select> Is there a way to do this and also include a value in each of the <option> tags like so? <select name="ReportedIssue" id="ReportedIssue"><option>All</option> <option value="0">All</option> <option value="1">...</option> </select> Thank you, Aaron

    Read the article

  • Multiple Actions (Forms) on one Page - How not to lose master data, after editing detail data?

    - by nWorx
    Hello all, I've got a form where users can edit members of a group. So they have the possibilty to add members or remove existing members. So the Url goes like ".../Group/Edit/4" Where 4 is the id of the group. the view looks like this <% using (Html.BeginForm("AddUser", "Group")) %> <%{%> <label for="newUser">User</label> <%=Html.TextBox("username")%> <input type="submit" value="Add"/> </div> <%}%> <% using (Html.BeginForm("RemoveUser", "Group")) %> <%{%> <div class="inputItem"> <label for="groupMember">Bestehende Mitglieder</label> <%= Html.ListBox("groupMember", from g in Model.GetMembers() select new SelectListItem(){Text = g}) %> <input type="submit" value="Remove" /> </div> <%}%> The problem is that after adding or removing one user i lose the id of the group. What is the best solution for solving this kind of problem? Should I use hidden fields to save the group id? Thanks in advance.

    Read the article

  • ASP.net MVC Routing on Postback

    - by Mark Kadlec
    In my ASP.net MVC View I have a dropdown that I want to get details on selection and asynchronously update a div. My aspx is as follows: <% using (Html.BeginForm("Index", "Portal", FormMethod.Post, new { id = "TheForm" })) {%> <h2>Index</h2> <% using (Ajax.BeginForm("Details", new AjaxOptions { UpdateTargetId = "mpkResults" })) { %> <%=Html.DropDownList("Docs", (IEnumerable<SelectListItem>)ViewData["Docs"], new { onchange = "document.getElementById('TheForm').submit();" })%> <p><input type="submit" value="Details" /></p> <% } %> <div id="mpkResults" style="margin:10px 0px 0px 0px;"></div> ... The onchange event fires correctly on selection of the dropdown, but instead of the Details method in my code behind firing, it hits my Index method. Why is the details method not getting hit on the onchange event? My Details() method in the controller is: public ActionResult Details() { ... < It never gets here, just goes to the index() method } It's a little frustrating right now since I'm sure it is a simple mistake but not sure what it could be. I looked at the Source of my page and sure enough, the form looks like it should be routing to the Details Action: <form action="/Portal/Details" method="post" ... Any help would be appreciated.

    Read the article

  • Asp.Net MVC3 - How create Dynamic DropDownList

    - by Bibo
    I found many articles on this but still I don´t know how exactly to do this. I am trying to create my own blog engine, I have View for create article (I am using EF and Code first) and now I must fill number of category in which article should be add but I want to change it to dropdownlist with names of categories. My model looks this: public class Article { public int ArticleID { get; set; } [Required] public string Title { get; set; } [Required] public int CategoryID { get; set; } public DateTime Date { get; set; } [Required()] [DataType(DataType.MultilineText)] [AllowHtml] public string Text { get; set; } public virtual Category Category { get; set; } public IEnumerable<SelectListItem> Categories { get; set; } public virtual ICollection<Comment> Comments { get; set; } } public class Category { public int CategoryID { get; set; } [Required] public string Name { get; set; } public virtual ICollection<Article> Articles { get; set; } } I know I must use Enum (or I think) but I am not exactly sure how. I don´t know which tutorial from that I found is best for me.

    Read the article

< Previous Page | 1 2 3 4  | Next Page >