Search Results

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

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

  • how do you reuse a partial view with setting different ids

    - by oo
    i have a partial view with a dropdown in it. the code looks like this: <%=Html.DropDownListFor(x => Model.Exercises, new SelectList(Model.Exercises, "Id", "Name", Model.SelectedExercise), new { @id = "exerciseDropdown", @class = "autoComplete" })%> the issue is that i want to reuse this partial view in multiple places but i want to have a different id assigned to the control (instead of exerciseDropdown always) but on the outside i only have this . . <% Html.RenderPartial("ExerciseList", Model); %> is there anyway to pass in an id into a partial view. is there a standard way to inject the ids into a partial view ? right now i am doing things like this: <% Html.RenderPartial("ExerciseList", Model); %> <% Html.RenderPartial("ExerciseList2", Model); %> where ExerciseList and ExerciseList2 are identical but with different ids but i am sure there is a better way.

    Read the article

  • MVC3 Razor DropDownListFor Enums

    - by jordan.baucke
    Trying to get my project updated to MVC3, something I just can't find: I have a simple datatype of ENUMS: public enum States() { AL,AK,AZ,...WY } Which I want to use as a DropDown/SelectList in my view of a model that contains this datatype: public class FormModel() { public States State {get; set;} } Pretty straight forward: when I go to use the auto-generate view for this partial class, it ignores this type. I need a simple select list that sets the value of the enum as the selected item when I hit submit and process via my AJAX - JSON POST Method. And than the view (???!): <div class="editor-field"> @Html.DropDownListFor(model => model.State, model => model.States) </div> thanks in advance for the advice!

    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

  • No Parameterless Constructor defined for - ViewModel with UOW

    - by TheVillageIdiot
    I have a view model class which uses UnitOfWork to some database operations like fetching of items to create select lists and IPrincipal for some auditing (like modified by etc.). It cannot work without this UOW. I have configured my web site to use Ninject to inject UOW into Controllers. From controller I pass this UOW when creating view model. But when performing POST operation I am getting No parameterless constructor defined for this object. I have few SelectList type of properties which I have excluded with Bind attribute. How can I overcome this problem? Can I configure Ninject to create the objects of this type and make ModelBinder use it?

    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

  • how to display selected value in drop down list in asp.net mvc?

    - by Renu123
    i want to display selected value in drop down list . the value comes from the data base. for ex suppose we want to update user profile then value for gender which is previously provided by the user should get displayed as selected value. the code that i used to display is <% string val = Convert.ToString(Model.gender); ViewData["gen"] = val; %> <%= Html.DropDownList("genderList", ViewData["gen"] as SelectList) %> but its not showing the value from the database.but viewdata get value from database but it is not showing on drop down list. thanks in advance.

    Read the article

  • knockout.js with optionsValue and value

    - by Mike Flynn
    Is there a way to keep the value binding to the object, but have the optionsValue be a property on the object. As of now if I specify both, the optionsValue property that is selected will populate the value binding. Id like to keep the object intact in the observable, but specify what value to be set in the select list value. This way a form submit will send the optionsValue I chose. @Html.DropDownListFor(q => q.DivisionId, new SelectList(Enumerable.Empty<string>()), new { data_bind="options: divisions, optionsText: 'Name', optionsValue: 'Id', value: division, optionsCaption: ' - '" }) function AddCrossPoolGameDialog() { var self = this; self.divisions = ko.observableArray([]); self.division = ko.observable(); self.awayDivisionTeams = ko.computed(function () { var division = ko.utils.arrayFirst(self.divisions(), function(item) { return self.division.Name() == item.Name; }); if (division) { return division.DivisionTeamPools; } return []; }); }

    Read the article

  • ASP.Net MVC2 CustomModelBinder not working... Changed from MVC1

    - by Ian
    (My apologies if this seems verbose - trying to provide all relevant code) I've just upgraded to VS2010, and am now having trouble trying to get a new CustomModelBinder working. In MVC1 I would have written something like public class AwardModelBinder: DefaultModelBinder { : public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { // do the base binding to bind all simple types Award award = base.BindModel(controllerContext, bindingContext) as Award; // Get complex values from ValueProvider dictionary award.EffectiveFrom = Convert.ToDateTime(bindingContext.ValueProvider["Model.EffectiveFrom"].AttemptedValue.ToString()); string sEffectiveTo = bindingContext.ValueProvider["Model.EffectiveTo"].AttemptedValue.ToString(); if (sEffectiveTo.Length > 0) award.EffectiveTo = Convert.ToDateTime(bindingContext.ValueProvider["Model.EffectiveTo"].AttemptedValue.ToString()); // etc return award; } } Of course I'd register the custom binder in Global.asax.cs: protected void Application_Start() { RegisterRoutes(RouteTable.Routes); // register custom model binders ModelBinders.Binders.Add(typeof(Voucher), new VoucherModelBinder(DaoFactory.UserInstance("EH1303"))); ModelBinders.Binders.Add(typeof(AwardCriterion), new AwardCriterionModelBinder(DaoFactory.UserInstance("EH1303"), new VOPSDaoFactory())); ModelBinders.Binders.Add(typeof(SelectedVoucher), new SelectedVoucherModelBinder(DaoFactory.UserInstance("IT0706B"))); ModelBinders.Binders.Add(typeof(Award), new AwardModelBinder(DaoFactory.UserInstance("IT0706B"))); } Now, in MVC2, I'm finding that my call to base.BindModel returns an object where everything is null, and I simply don't want to have to iterate all the form fields surfaced by the new ValueProvider.GetValue() function. Google finds no matches for this error, so I assume I'm doing something wrong. Here's my actual code: My domain object (infer what you like about the encapsulated child objects - I know I'll need custom binders for those too, but the three "simple" fields (ie. base types) Id, TradingName and BusinessIncorporated are also coming back null): public class Customer { /// <summary> /// Initializes a new instance of the Customer class. /// </summary> public Customer() { Applicant = new Person(); Contact = new Person(); BusinessContact = new ContactDetails(); BankAccount = new BankAccount(); } /// <summary> /// Gets or sets the unique customer identifier. /// </summary> public int Id { get; set; } /// <summary> /// Gets or sets the applicant details. /// </summary> public Person Applicant { get; set; } /// <summary> /// Gets or sets the customer's secondary contact. /// </summary> public Person Contact { get; set; } /// <summary> /// Gets or sets the trading name of the business. /// </summary> [Required(ErrorMessage = "Please enter your Business or Trading Name")] [StringLength(50, ErrorMessage = "A maximum of 50 characters is permitted")] public string TradingName { get; set; } /// <summary> /// Gets or sets the date the customer's business began trading. /// </summary> [Required(ErrorMessage = "You must supply the date your business started trading")] [DateRange("01/01/1900", "01/01/2020", ErrorMessage = "This date must be between {0} and {1}")] public DateTime BusinessIncorporated { get; set; } /// <summary> /// Gets or sets the contact details for the customer's business. /// </summary> public ContactDetails BusinessContact { get; set; } /// <summary> /// Gets or sets the customer's bank account details. /// </summary> public BankAccount BankAccount { get; set; } } My controller method: /// <summary> /// Saves a Customer object from the submitted application form. /// </summary> /// <param name="customer">A populate instance of the Customer class.</param> /// <returns>A partial view indicating success or failure.</returns> /// <httpmethod>POST</httpmethod> /// <url>/Customer/RegisterCustomerAccount</url> [HttpPost] [ValidateAntiForgeryToken] public ActionResult RegisterCustomerAccount(Customer customer) { if (ModelState.IsValid) { // save the Customer // return indication of success, or otherwise return PartialView(); } else { ViewData.Model = customer; // load necessary reference data into ViewData ViewData["PersonTitles"] = new SelectList(ReferenceDataCache.Get("PersonTitle"), "Id", "Name"); return PartialView("CustomerAccountRegistration", customer); } } My custom binder: public class CustomerModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { ValueProviderResult vpResult = bindingContext .ValueProvider.GetValue(bindingContext.ModelName); // vpResult is null // MVC2 - ValueProvider is now an IValueProvider, not dictionary based anymore if (bindingContext.ValueProvider.GetValue("Model.Applicant.Title") != null) { // works } Customer customer = base.BindModel(controllerContext, bindingContext) as Customer; // customer instanitated with null (etc) throughout return customer; } } My binder registration: /// <summary> /// Application_Start is called once when the web application is first accessed. /// </summary> protected void Application_Start() { RegisterRoutes(RouteTable.Routes); // register custom model binders ModelBinders.Binders.Add(typeof(Customer), new CustomerModelBinder()); ReferenceDataCache.Populate(); } ... and a snippet from my view (could this be a prefix problem?) <div class="inputContainer"> <label class="above" for="Model_Applicant_Title" accesskey="t"><span class="accesskey">T</span>itle<span class="mandatoryfield">*</span></label> <%= Html.DropDownList("Model.Applicant.Title", ViewData["PersonTitles"] as SelectList, "Select ...", new { @class = "validate[required]" })%> <% Html.ValidationMessageFor(model => model.Applicant.Title); %> </div> <div class="inputContainer"> <label class="above" for="Model_Applicant_Forename" accesskey="f"><span class="accesskey">F</span>orename / First name<span class="mandatoryfield">*</span></label> <%= Html.TextBox("Model.Applicant.Forename", Html.Encode(Model.Applicant.Forename), new { @class = "validate[required,custom[onlyLetter],length[2,20]]", title="Enter your forename", maxlength = 20, size = 20, autocomplete = "off", onkeypress = "return maskInput(event,re_mask_alpha);" })%> </div> <div class="inputContainer"> <label class="above" for="Model_Applicant_MiddleInitials" accesskey="i">Middle <span class="accesskey">I</span>nitial(s)</label> <%= Html.TextBox("Model.Applicant.MiddleInitials", Html.Encode(Model.Applicant.MiddleInitials), new { @class = "validate[optional,custom[onlyLetter],length[0,8]]", title = "Please enter your middle initial(s)", maxlength = 8, size = 8, autocomplete = "off", onkeypress = "return maskInput(event,re_mask_alpha);" })%> </div>

    Read the article

  • how to reload jqgrid in asp.net mvc when i change dropdownlist

    - by sandeep
    what is wrong in this code? when i change drop down list,the grid takes old value of ddl only, not taken newely selected values why? <%--<asp:Content ID="Content2script" ContentPlaceHolderID="HeadScript" runat="server"> <script type="text/javascript"> $(function() { $("#StateId").change(function() { $('#TheForm').submit(); }); }); $(function() { $("#CityId").change(function() { $('#TheForm').submit(); }); }); $(function() { $("#HospitalName").change(function() { $('#TheForm').submit(); }); }); </script > </asp:Content>--%> <asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server"> <link rel="stylesheet" type="text/css" href="/scripts/themes/coffee/grid.css" title="coffee" media="screen" /> <script src="/Scripts/jquery-1.3.2.js" type="text/javascript"></script> <script src="/Scripts/jquery.jqGrid.js" type="text/javascript"></script> <script src="/Scripts/js/jqModal.js" type="text/javascript"></script> <script src="/Scripts/js/jqDnR.js" type="text/javascript"></script> <script type="text/javascript"> var gridimgpath = '/scripts/themes/coffee/images'; var gridDataUrl = '/Claim/DynamicGridData/'; jQuery(document).ready(function() { // $("#btnSearch").click(function() { var StateId = document.getElementById('StateId').value; var CityId = document.getElementById('CityId').value; var HName = document.getElementById('HospitalName').value; // alert(CityId); // alert(StateId); // alert(HName); if (StateId > 0 && CityId == '' && HName == '') { CityId = 0; HName = 'Default'.toString(); // alert("elseif0" + HName.toString()); } else if (CityId > 0 && StateId == '') { // alert("elseif1"); alert("Please Select State..") } else if (CityId > 0 && StateId > 0 && HName == '') { // alert("elseif2"); alert(CityId); alert(StateId); HName = "Default"; } else { // alert("else"); StateId = 0; CityId = 0; HName = "Default"; } jQuery("#list").jqGrid({ url: gridDataUrl + '?StateId=' + StateId + '&CityId=' + CityId + '&hospname=' + HName, datatype: 'json', mtype: 'GET', colNames: ['Id', 'HospitalName', 'Address', 'City', 'District', 'FaxNumber', 'PhoneNumber'], colModel: [{ name: 'HospitalId', index: 'HospitalId', width: 40, align: 'left' }, { name: 'HospitalName', index: 'HospitalName', width: 40, align: 'left' }, { name: 'Address1', Address: 'Address1', width: 300 }, { name: 'CityName', index: 'CityName', width: 100 }, { name: 'DistName', index: 'DistName', width: 100 }, { name: 'FaxNo', index: 'FaxNo', width: 100 }, { name: 'ContactNo1', index: 'PhoneNumber', width: 100 } ], pager: jQuery('#pager'), rowNum: 10, rowList: [5, 10, 20, 50], // sortname: 'Id,', sortname: '1', sortorder: "asc", viewrecords: true, //multiselect: true, //multikey: "ctrlKey", // imgpath: '/scripts/themes/coffee/images', imgpath: gridimgpath, caption: 'Hospital Search', width: 700, height: 250 }); $(function() { // $("#btnSearch").click(function() { $('#CityId').change(function() { alert("kjasd"); // Set the vars whenever the date range changes and then filter the results StateId = document.getElementById('StateId').value; CityId = document.getElementById('CityId').value; HName = 'default'; setGridUrl(); }); // Set the date range textbox values $('#StateId').val(StateId.toString()); $('#CityId').val(CityId.toString()); // Set the grid json url to get the data to display setGridUrl(); }); function setGridUrl() { alert(StateId); alert(CityId); alert("hi"); var newGridDataUrl = gridDataUrl + '?StateId=' + StateId + '&CityId=' + CityId + '&hospname=' + HName; jQuery('#list').jqGrid('setGridParam', { url: newGridDataUrl }).trigger("reloadGrid"); } // }); }); </script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <%--<%using (Html.BeginForm("HospitalSearch", "Claim", FormMethod.Post, new { id = "TheForm" })) --%> <table cellspacing="0" cellpadding="2" width="100%" border="0" > <tr> <td class ="Heading1"> Hospital Search</td> <td class ="Heading1" align="right" width="50%" background="../images/homebg.gif"> &nbsp; </td> </tr> <tr> <td colspan="2" > <% Html.RenderPartial("InsuredDetails"); %> </td> </tr> <tr> <td colspan="2"> <table width="100%"> <tr> <td class="subline" valign="middle"> State : <% =Html.DropDownList("StateId", (SelectList)ViewData["States"], "--Select--", new { @class = "ddownmenu" })%> &nbsp; City : <% =Html.DropDownList("CityId", (SelectList)ViewData["Cities"], "--Select--", new { @class = "ddownmenu" })%> &nbsp; Hospital Name : <% =Html.TextBox("HospitalName")%> &nbsp; &nbsp; <input id="btnSearch" type="submit" value="Search" /> </td> </tr> </table> </td> </tr> <tr> <td align="center" colspan="2"> &nbsp;</td> </tr> </table> <div id="jqGridContainer"> <table id="list" class="scroll" cellpadding="0" cellspacing="0"></table> <div id="pager" class="scroll" style="text-align:center;"></div> </div> </asp:Content>

    Read the article

  • MVC 2 Entity Framework View Model Insert

    - by cannibalcorpse
    This is driving me crazy. Hopefully my question makes sense... I'm using MVC 2 and Entity Framework 1 and am trying to insert a new record with two navigation properties. I have a SQL table, Categories, that has a lookup table CategoryTypes and another self-referencing lookup CategoryParent. EF makes two nav properties on my Category model, one called Parent and another called CategoryType, both instances of their respective models. On my view that creates the new Category, I have two dropdowns, one for the CategoryType and another for the ParentCategory. When I try and insert the new Category WITHOUT the ParentCategory, which allows nulls, everything is fine. As soon as I add the ParentCategory, the insert fails, and oddly (or so I think) complains about the CategoryType in the form of this error: 0 related 'CategoryTypes' were found. 1 'CategoryTypes' is expected. When I step through, I can verifiy that both ID properties coming in on the action method parameter are correct. I can also verify that when I go to the db to get the CategoryType and ParentCategory with the ID's, the records are being pulled fine. Yet it fails on SaveChanges(). All that I can see is that my CategoryParent dropdownlistfor in my view, is somehow causing the insert to bomb. Please see my comments in my httpPost Create action method. My view model looks like this: public class EditModel { public Category MainCategory { get; set; } public IEnumerable<CategoryType> CategoryTypesList { get; set; } public IEnumerable<Category> ParentCategoriesList { get; set; } } My Create action methods look like this: // GET: /Categories/Create public ActionResult Create() { return View(new EditModel() { CategoryTypesList = _db.CategoryTypeSet.ToList(), ParentCategoriesList = _db.CategorySet.ToList() }); } // POST: /Categories/Create [HttpPost] public ActionResult Create(Category mainCategory) { if (!ModelState.IsValid) return View(new EditModel() { MainCategory = mainCategory, CategoryTypesList = _db.CategoryTypeSet.ToList(), ParentCategoriesList = _db.CategorySet.ToList() }); mainCategory.CategoryType = _db.CategoryTypeSet.First(ct => ct.Id == mainCategory.CategoryType.Id); // This db call DOES get the correct Category, but fails on _db.SaveChanges(). // Oddly the error is related to CategoryTypes and not Category. // Entities in 'DbEntities.CategorySet' participate in the 'FK_Categories_CategoryTypes' relationship. // 0 related 'CategoryTypes' were found. 1 'CategoryTypes' is expected. //mainCategory.Parent = _db.CategorySet.First(c => c.Id == mainCategory.Parent.Id); // If I just use the literal ID of the same Category, // AND comment out the CategoryParent dropdownlistfor in the view, all is fine. mainCategory.Parent = _db.CategorySet.First(c => c.Id == 2); _db.AddToCategorySet(mainCategory); _db.SaveChanges(); return RedirectToAction("Index"); } Here is my Create form on the view : <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div> <%= Html.LabelFor(model => model.MainCategory.Parent.Id) %> <%= Html.DropDownListFor(model => model.MainCategory.Parent.Id, new SelectList(Model.ParentCategoriesList, "Id", "Name")) %> <%= Html.ValidationMessageFor(model => model.MainCategory.Parent.Id) %> </div> <div> <%= Html.LabelFor(model => model.MainCategory.CategoryType.Id) %> <%= Html.DropDownListFor(model => model.MainCategory.CategoryType.Id, new SelectList(Model.CategoryTypesList, "Id", "Name"))%> <%= Html.ValidationMessageFor(model => model.MainCategory.CategoryType.Id)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.Name) %> <%= Html.TextBoxFor(model => model.MainCategory.Name)%> <%= Html.ValidationMessageFor(model => model.MainCategory.Name)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.Description)%> <%= Html.TextAreaFor(model => model.MainCategory.Description)%> <%= Html.ValidationMessageFor(model => model.MainCategory.Description)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.SeoName)%> <%= Html.TextBoxFor(model => model.MainCategory.SeoName, new { @class = "large" })%> <%= Html.ValidationMessageFor(model => model.MainCategory.SeoName)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.HasHomepage)%> <%= Html.CheckBoxFor(model => model.MainCategory.HasHomepage)%> <%= Html.ValidationMessageFor(model => model.MainCategory.HasHomepage)%> </div> <p><input type="submit" value="Create" /></p> </fieldset> <% } %> Maybe I've just been staying up too late playing with MVC 2? :) Please let me know if I'm not being clear enough.

    Read the article

  • ASP.NET MVC validation problem

    - by ile
    ArticleRepostitory.cs: using System; using System.Collections.Generic; using System.Linq; using System.Web; using CMS.Model; using System.Web.Mvc; namespace CMS.Models { public class ArticleDisplay { public ArticleDisplay() { } public int CategoryID { set; get; } public string CategoryTitle { set; get; } public int ArticleID { set; get; } public string ArticleTitle { set; get; } public DateTime ArticleDate; public string ArticleContent { set; get; } } public class ArticleRepository { private DB db = new DB(); // // Query Methods public IQueryable<ArticleDisplay> FindAllArticles() { var result = from category in db.ArticleCategories join article in db.Articles on category.CategoryID equals article.CategoryID select new ArticleDisplay { CategoryID = category.CategoryID, CategoryTitle = category.Title, ArticleID = article.ArticleID, ArticleTitle = article.Title, ArticleDate = article.Date, ArticleContent = article.Content }; return result; } public IQueryable<ArticleDisplay> FindTodayArticles() { var result = from category in db.ArticleCategories join article in db.Articles on category.CategoryID equals article.CategoryID where article.Date == DateTime.Today select new ArticleDisplay { CategoryID = category.CategoryID, CategoryTitle = category.Title, ArticleID = article.ArticleID, ArticleTitle = article.Title, ArticleDate = article.Date, ArticleContent = article.Content }; return result; } public Article GetArticle(int id) { return db.Articles.SingleOrDefault(d => d.ArticleID == id); } public IQueryable<ArticleDisplay> DetailsArticle(int id) { var result = from category in db.ArticleCategories join article in db.Articles on category.CategoryID equals article.CategoryID where id == article.ArticleID select new ArticleDisplay { CategoryID = category.CategoryID, CategoryTitle = category.Title, ArticleID = article.ArticleID, ArticleTitle = article.Title, ArticleDate = article.Date, ArticleContent = article.Content }; return result; } // // Insert/Delete Methods public void Add(Article article) { db.Articles.InsertOnSubmit(article); } public void Delete(Article article) { db.Articles.DeleteOnSubmit(article); } // // Persistence public void Save() { db.SubmitChanges(); } } } ArticleController.cs: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using CMS.Models; using CMS.Model; namespace CMS.Controllers { public class ArticleController : Controller { ArticleRepository articleRepository = new ArticleRepository(); ArticleCategoryRepository articleCategoryRepository = new ArticleCategoryRepository(); // // GET: /Article/ public ActionResult Index() { var allArticles = articleRepository.FindAllArticles().ToList(); return View(allArticles); } // // GET: /Article/Details/5 public ActionResult Details(int id) { var article = articleRepository.DetailsArticle(id).Single(); if (article == null) return View("NotFound"); return View(article); } // // GET: /Article/Create public ActionResult Create() { ViewData["categories"] = new SelectList ( articleCategoryRepository.FindAllCategories().ToList(), "CategoryId", "Title" ); Article article = new Article() { Date = DateTime.Now, CategoryID = 1 }; return View(article); } // // POST: /Article/Create [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Article article) { if (ModelState.IsValid) { try { // TODO: Add insert logic here articleRepository.Add(article); articleRepository.Save(); return RedirectToAction("Index"); } catch { return View(article); } } else { return View(article); } } // // GET: /Article/Edit/5 public ActionResult Edit(int id) { ViewData["categories"] = new SelectList ( articleCategoryRepository.FindAllCategories().ToList(), "CategoryId", "Title" ); var article = articleRepository.GetArticle(id); return View(article); } // // POST: /Article/Edit/5 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id, FormCollection collection) { Article article = articleRepository.GetArticle(id); try { // TODO: Add update logic here UpdateModel(article, collection.ToValueProvider()); articleRepository.Save(); return RedirectToAction("Details", new { id = article.ArticleID }); } catch { return View(article); } } // // HTTP GET: /Article/Delete/1 public ActionResult Delete(int id) { Article article = articleRepository.GetArticle(id); if (article == null) return View("NotFound"); else return View(article); } // // HTTP POST: /Article/Delete/1 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Delete(int id, string confirmButton) { Article article = articleRepository.GetArticle(id); if (article == null) return View("NotFound"); articleRepository.Delete(article); articleRepository.Save(); return View("Deleted"); } } } View/Article/Create.aspx: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<CMS.Model.Article>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Create </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Create</h2> <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %> <% using (Html.BeginForm()) {%> <fieldset> <legend>Fields</legend> <p> <label for="Title">Title:</label> <%= Html.TextBox("Title") %> <%= Html.ValidationMessage("Title", "*") %> </p> <p> <label for="Content">Content:</label> <%= Html.TextArea("Content", new { id = "Content" })%> <%= Html.ValidationMessage("Content", "*")%> </p> <p> <label for="Date">Date:</label> <%= Html.TextBox("Date") %> <%= Html.ValidationMessage("Date", "*") %> </p> <p> <label for="CategoryID">Category:</label> <%= Html.DropDownList("CategoryId", (IEnumerable<SelectListItem>)ViewData["categories"])%> </p> <p> <input type="submit" value="Create" /> </p> </fieldset> <% } %> <div> <%=Html.ActionLink("Back to List", "Index") %> </div> </asp:Content> If I remove DropDownList from .aspx file then validation (on date only because no other validation exists) works, but of course I can't create new article because one value is missing. If I leave dropdownlist and try to insert wrong date I get following error: System.InvalidOperationException: The ViewData item with the key 'CategoryId' is of type 'System.Int32' but needs to be of type 'IEnumerable'. If I enter correct date than the article is properly inserted. There's one other thing that's confusing me... For example, if I try manually add the categoyID: [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Article article) { if (ModelState.IsValid) { try { // TODO: Add insert logic here // Manually add category value article.CategoryID = 1; articleRepository.Add(article); articleRepository.Save(); return RedirectToAction("Index"); } catch { return View(article); } } else { return View(article); } } ..I also get the above error. There's one other thing I noticed. If I add partial class Article, when returning to articleRepository.cs I get error that 'Article' is an ambiguous reference between 'CMS.Models.Article' and 'CMS.Model.Article' Any thoughts on this one?

    Read the article

  • How could i get selected value from dropdownlist in kendo ui grid in mvc

    - by Karthik Bammidi
    I am working on Kendo UI with asp.net mvc razor. I am trying to bind database table data with kendo grid that supports CRUD operations. Here i need to populate a dropdownlist for one of my table field. I have used the following code View: @model IEnumerable<MvcApplication1.PriceOption> @(Html.Kendo().Grid(Model) .Name("Grid") .Columns(columns => { //columns.Bound(p => p.ProductTitle).ClientTemplate("<input type='checkbox' disabled='disabled'name='Discontinued' <#= Discontinued? checked='checked' : '' #> />"); columns.Bound(p => p.ProductTitle).EditorTemplateName("OptionalEmail"); columns.Bound(p => p.OptionTitle); columns.Bound(p => p.Price); columns.Bound(p => p.Frequency); columns.Command(command => { command.Edit(); command.Destroy(); }).Width(200); }) .ToolBar(toolbar => toolbar.Create()) .Editable(editable => editable.Mode(Kendo.Mvc.UI.GridEditMode.InLine)) .Pageable() .Sortable() .Scrollable() .DataSource(dataSource => dataSource .Ajax() .Events(events => events.Error("error_handler")) .Model(model => model.Id(p => p.ProductID)) .Create(create => create.Action("CreateOption", "ZiceAdmin")) .Read(read => read.Action("Read", "ZiceAdmin")) .Update(update => update.Action("UpdateOption", "ZiceAdmin")) .Destroy(update => update.Action("DeleteOption", "ZiceAdmin")) ) ) OptionalEmail.cshtml @model string @(Html.Kendo().DropDownList() .Name("ProductTitle") .Value(Model) .SelectedIndex(0) .BindTo(new SelectList(ViewBag.ProductTitle)) ) Here i need to store the selected item from the dropdownlist. But it always shows null. How could i get the selected value from dropdownlist.

    Read the article

  • ASP.NET MVC DropDownList SelectedValue works on Edit action, but not Create action

    - by davekaro
    I have the following code in my controller (for Edit and Create): model.Templates = new SelectList(PageManagementService.PageTemplateFetchList(), "PageId", "Title", 213); the "213" is an Id for one of the pages - just using it for testing. And this is in my view (for Edit and Create): <%= this.Html.DropDownListFor(model => model.Page.TemplateId, this.Model.Templates)%> <%= this.Model.Templates.SelectedValue %> When I go to the Create form, I see the dropdown list, but the tag with value="213" is not selected. I even output the SelectedValue to make sure it's 213 - and I see 213. When I go to the Edit form, I see the dropdown list, and the tag with value="213" is selected. On the Create form, none of the tags have a "selected" attribute. On the Edit form, the tag with value="213" has the "selected" attribute. Am I missing something? What could be causing this? Anyone see this behavior before?

    Read the article

  • ASP.NET MVC 2 - Html.DropDownList not working in an AJAX form

    - by Jacob
    I am trying to create an MVC 2 solution and I have run into the following problem: Index.aspx: <% using(Ajax.BeginForm("Forms", new AjaxOptions{UpdateTargetId="form", HttpMethod="POST"})) { %> <h3>Input: </h3> <p><%= Html.DropDownList("dropDown")%> <input type="submit" value="Select Mission" /></p> <% } %> HomeController.cs: public ActionResult Index() { var list = new [] { "item1", "item2", "item3" }; ViewData["dropDown"] = new SelectList(list); return View(); } public ActionResult Forms(string dropDown) { if (dropDown == null || dropDown == "") ViewData["txt"] = "Ahhh..."; else ViewData["txt"] = "You entered: " + dropDown; return PartialView("Form", dropDown); } Form.ascx: <%: ViewData["txt"] % This does not work. However, the whole thing does work if I use an Html.TextBox instead. For example: <div id="form"> <% using(Ajax.BeginForm("Forms", new AjaxOptions{UpdateTargetId="form", HttpMethod="POST"})) { %> <h3>Input: </h3> <%= Html.TextBox("textBox") %> <input type="submit" value="Select Mission" /></p> <% } %> </div> (and refactor the method in the controller so that it's argument is textBox instead of dropDown). My question is why does the AJAX form work for an Html.TextBox, but not for an Html.DropDownList, or what am I doing wrong? My only idea is that maybe the argument in the controller is not supposed to be of type string when using a DropDownList, but this is really just a guess. Thanks in advance.

    Read the article

  • Ajax actionlinks straight from a DropDownList

    - by Ingó Vals
    I've got a small linkbox on the side of my page that is rendered as a PartialView. In it I have a dropDownlist the should change the routing value of the links in the box but I'm having difficulty doing so. My current plan is to call on something similar to a Ajax.ActionLink to reload the partial view into the with a different parameter based on the value of the dropdown selection. However I'm having multiple problems with this, for example as a novice in using dropdownlists I have no idea how to call on the selected value for example. <%= Html.DropDownList("DropDownList1", new SelectList(Model, "ID", "Name"), "--Pick--", new { AutoPostBack = "true", onchange = "maybe something here" })%> I tried putting in the sys.mvc.AsyncHyperlink into the onchange attribute and that worked except I don't know how to put in the route value for it. Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: 'SmallMenu' } Is there no straight Ajax drop down list that fires events onchange? Any way this is possible? I have later in the Partial view the Ajax actionlinks but they need to have their id's updated by the value in the dropdownlist and if I could do that somehow else I would appreciate a suggestion.

    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

  • BindAttribute, Exclude nested properties for complex types

    - by David Board
    I have a 'Stream' model: public class Stream { public int ID { get; set; } [Required] [StringLength(50, ErrorMessage = "Stream name cannot be longer than 50 characters.")] public string Name { get; set; } [Required] [DataType(DataType.Url)] public string URL { get; set; } [Required] [Display(Name="Service")] public int ServiceID { get; set; } public virtual Service Service { get; set; } public virtual ICollection<Event> Events { get; set; } public virtual ICollection<Monitor> Monitors { get; set; } public virtual ICollection<AlertRule> AlertRules { get; set; } } For the 'create' view for this model, I have made a view model to pass some additional information to the view: public class StreamCreateVM { public Stream Stream { get; set; } public SelectList ServicesList { get; set; } public int SelectedService { get; set; } } Here is my create post action: [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include="Stream, Stream.Name, Stream.ServiceID, SelectedService")] StreamCreateVM viewModel) { if (ModelState.IsValid) { db.Streams.Add(viewModel.Stream); db.SaveChanges(); return RedirectToAction("Index", "Service", new { id = viewModel.Stream.ServiceID }); } return View(viewModel); } Now, this all works, apart from the [Bind(Include="Stream, Stream.Name, Stream.ServiceID, SelectedService")] bit. I can't seem to Include or Exclude properties within a nested object.

    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

  • DropDownListFor and relating my lambda to my ViewModel

    - by Daniel Harvey
    After googling for a while I'm still drawing a blank here. I'm trying to use a ViewModel to pull and provide a dictionary to a drop down list inside a strongly typed View: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="Notebook.ViewModels.CorporationJoinViewModel" %> ... <%: Html.DropDownListFor(c => c.CorpDictionary.Keys, new SelectList(Model.CorpDictionary, "Value", "Key"))%> I'm getting the error CS1061: 'object' does not contain a definition for 'CorpDictionary' and no extension method 'CorpDictionary' accepting a first argument of type 'object' could be found and the relevant bit of my ViewModel public class CorporationJoinViewModel { DB _db = new DB(); // data context public Dictionary<int, string> CorpDictionary { get { Dictionary<int, string> corporations = new Dictionary<int, string>(); int x = 0; foreach (Corporation corp in _db.Corporations) { corporations.Add(x, corp.name); } return corporations; } } I'll admit i have a pretty magical understanding of how linq is finding my ViewModel object from that lambda, and the error message is making me think it's not. Is my problem the method I'm using to pass the data? What am I missing here?

    Read the article

  • Entity Framework with ASP.NET MVC. Updating entity problem

    - by Kitaly
    Hi people. I'm trying to update an entity and its related entities as well. For instance, I have a class Car with a property Category and I want to change its Category. So, I have the following methods in the Controller: public ActionResult Edit(int id) { var categories = context.Categories.ToList(); ViewData["categories"] = new SelectList(categories, "Id", "Name"); var car = context.Cars.Where(c => c.Id == id).First(); return PartialView("Form", car); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(Car car) { var category = context.Categories.Where(c => c.Id == car.Category.Id).First(); car.Category = category; context.UpdateCar(car); context.SaveChanges(); return RedirectToAction("Index"); } The UpdateCar method, in ObjectContext class, follows: public void UpdateCar(Car car) { var attachedCar = Cars.Where(c => c.Id == car.Id).First(); ApplyItemUpdates(attachedCar, car); } private void ApplyItemUpdates(EntityObject originalItem, EntityObject updatedItem) { try { ApplyPropertyChanges(originalItem.EntityKey.EntitySetName, updatedItem); ApplyReferencePropertyChanges(updatedItem, originalItem); } catch (InvalidOperationException ex) { Console.WriteLine(ex.ToString()); } } public void ApplyReferencePropertyChanges(IEntityWithRelationships newEntity, IEntityWithRelationships oldEntity) { foreach (var relatedEnd in oldEntity.RelationshipManager.GetAllRelatedEnds()) { var oldRef = relatedEnd as EntityReference; if (oldRef != null) { var newRef = newEntity.RelationshipManager.GetRelatedEnd(oldRef.RelationshipName, oldRef.TargetRoleName) as EntityReference; oldRef.EntityKey = newRef.EntityKey; } } } The problem is that when I set the Category property after the POST in my controller, the entity state changes to Added instead of remaining as Detached. How can I update one-to-one relationship with Entity Framework and ASP.NET MVC without setting all the properties, one by one like this post?

    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

  • A dropdownlist list in ASP.NET MVC although not [required] field shows up as required and Model Sta

    - by VJ
    I have the following code- View- <% Html.BeginForm(); %> <div> <%= Html.DropDownList("DropDownSelectList", new SelectList( Model.DropDownSelectList, "Value", "Text"))%> Controller- public ActionResult Admin(string apiKey, string userId) { ChallengesAdminViewModel vm = new ChallengesAdminViewModel(); vm.ApiKey = apiKey; vm.UserId = userId; vm.DropDownSelectList = new List<SelectListItem>(); vm.DropDownSelectList.Add(listItem1); vm.DropDownSelectList.Add(listItem2); vm.DropDownSelectList.Add(listItem3); vm.DropDownSelectList.Add(listItem4); vm.DropDownSelectList.Add(listItem5); vm.DropDownSelectList.Add(listItem6); vm.DropDownSelectList.Add(listItem7); } [HttpPost] public ActionResult Admin(ChallengesAdminViewModel vm) { if (ModelState.IsValid)//Due to the null dropdownlist gives model state invalid { } } ViewModel- public class ChallengesAdminViewModel { [Required] public string ApiKey { get; set; } [Required] public string UserId { get; set; } public List<SelectListItem> DropDownSelectList { get; set; } } I dont know why it still requires the list although not required. I want to have only two attributes as required. So I wanted to know how do i declare or change that list to be not required and have my Model State Valid.

    Read the article

  • Although not [required] List field shows up as required and Model State is not Valid due to it bein

    - by VJ
    I have the following code- View- <% Html.BeginForm(); %> <div> <%= Html.DropDownList("DropDownSelectList", new SelectList( Model.DropDownSelectList, "Value", "Text"))%> Controller- public ActionResult Admin(string apiKey, string userId) { ChallengesAdminViewModel vm = new ChallengesAdminViewModel(); vm.ApiKey = apiKey; vm.UserId = userId; vm.DropDownSelectList = new List<SelectListItem>(); vm.DropDownSelectList.Add(listItem1); vm.DropDownSelectList.Add(listItem2); vm.DropDownSelectList.Add(listItem3); vm.DropDownSelectList.Add(listItem4); vm.DropDownSelectList.Add(listItem5); vm.DropDownSelectList.Add(listItem6); vm.DropDownSelectList.Add(listItem7); } [HttpPost] public ActionResult Admin(ChallengesAdminViewModel vm) { if (ModelState.IsValid)//Due to the null dropdownlist gives model state invalid { } } ViewModel- public class ChallengesAdminViewModel { [Required] public string ApiKey { get; set; } [Required] public string UserId { get; set; } public List<SelectListItem> DropDownSelectList { get; set; } } I dont know why it still requires the list although not required. I want to have only two attributes as required. So I wanted to know how do i declare or change that list to be not required and have my Model State Valid.

    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

  • Populating dropdownlist in asp.net mvc doesn't seem to work for me...

    - by Pandiya Chendur
    I use a dropdownlist in one of my create.aspx but it some how doesnt seem to work... public IEnumerable<Materials> FindAllMeasurements() { var mesurements = from mt in db.MeasurementTypes select new Materials() { Id= Convert.ToInt64(mt.Id), Mes_Name= mt.Name }; return mesurements; } and my controller, public ActionResult Create() { var mesurementTypes = consRepository.FindAllMeasurements().AsEnumerable(); ViewData["MeasurementType"] = new SelectList(mesurementTypes, "Id", "Mes_Name"); return View(); } and my create.aspx has this, <p> <label for="MeasurementTypeId">MeasurementType:</label> <%= Html.DropDownList("MeasurementType", ViewData["MeasurementType"])%> <%= Html.ValidationMessage("MeasurementTypeId", "*") %> </p> When i execute this i got these errors, System.Web.Mvc.HtmlHelper<CrMVC.Models.Material>' does not contain a definition for 'DropDownList' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.DropDownList(System.Web.Mvc.HtmlHelper, string, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>)' has some invalid arguments 2.cannot convert from 'object' to 'System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>

    Read the article

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