Search Results

Search found 386 results on 16 pages for 'viewdata'.

Page 3/16 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • 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

  • Asp.Net MVC - Rob Conery's LazyList - Count() or Count

    - by Adam
    I'm trying to create an html table for order logs for customers. A customer is defined as (I've left out a lot of stuff): public class Customer { public LazyList<Order> Orders { get; set; } } The LazyList is set when fetching a Customer: public Customer GetCustomer(int custID) { Customer c = ... c.Orders = new LazyList<Order>(_repository.GetOrders().ByOrderID(custID)); return c; } The order log model: public class OrderLogTableModel { public OrderLogTableModel(LazyList<Order> orders) { Orders = orders; Page = 0; PageSize = 25; } public LazyList<Order> Orders { get; set; } public int Page { get; set; } public int PageSize { get; set; } } and I pass in the customer.Orders after loading a customer. Now the log i'm trying to make, looks something like: <table> <tbody> <% int rowCount = ViewData.Model.Orders.Count(); int innerRows = rowCount - (ViewData.Model.Page * ViewData.Model.PageSize); foreach (Order order in ViewData.Model.Orders.OrderByDescending(x => x.StartDateTime) .Take(innerRows).OrderBy(x => x.StartDateTime) .Take(ViewData.Model.PageSize)) { %> <tr> <td> <%= order.ID %> </td> </tr> <% } %> </tbody> </table> Which works fine. But the problem is evaluating ViewData.Model.Orders.Count() literally takes about 10 minutes. I've tried with the ViewData.Model.Orders.Count property instead, and the results are the same - takes forever. I've also tried calling _repository.GetOrders().ByCustomerID(custID).Count() directly from the view and that executes perfectly within a few ms. Can anybody see any reason why using the LazyList to get a simple count would take so long? It seems like its trying to iterate through the list when getting a simple count.

    Read the article

  • Why is Html.DropDownList() producing <select name="original_name.name"> instead of just <select name

    - by DanM
    I have an editor template whose job is to take a SelectList as its model and build a select element in html using the Html.DropDownList() helper extension. I'm trying to assign the name attribute for the select based on a ModelMetadata property. (Reason: on post-back, I need to bind to an object that has a different property name for this item than the ViewModel used to populate the form.) The problem I'm running into is that DropDownList() is appending the name I'm providing instead of replacing it, so I end up with names like categories.category instead of category. Here is some code for you to look at... SelectList.ascx <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Web.Mvc.SelectList>" %> <%= Html.DropDownList( (string)ViewData.ModelMetadata.AdditionalValues["PropertyName"], Model) %> Resulting HTML <select id="SkillLevels_SkillLevel" name="SkillLevels.SkillLevel"> <option value="1">High</option> <option value="2">Med</option> <option selected="selected" value="3">Low</option> </select> Expected HTML <select id="SkillLevels_SkillLevel" name="SkillLevel"> <option value="1">High</option> <option value="2">Med</option> <option selected="selected" value="3">Low</option> </select> Also tried <%= Html.Encode((string)ViewData.ModelMetadata.AdditionalValues["PropertyName"])%> ...which resulted in "SkillLevel" (not "SkillLevels.SkillLevel"), proving that the data stored in metadata is correct. and <%= Html.DropDownList( (string)ViewData.ModelMetadata.AdditionalValues["PropertyName"], Model, new { name = (string)ViewData.ModelMetadata.AdditionalValues["PropertyName"] }) %> ...which still resulted in <select name=SkillLevels.Skilllevel>. Questions What's going on here? Why does it append the name instead of just using it? Can you suggest a good workaround? Update: I ended up writing a helper extension that literally does a find/replace on the html text: public static MvcHtmlString BindableDropDownListForModel(this HtmlHelper helper) { var propertyName = (string)helper.ViewData.ModelMetadata.AdditionalValues["PropertyName"]; var compositeName = helper.ViewData.ModelMetadata.PropertyName + "." + propertyName; var rawHtml = helper.DropDownList(propertyName, (SelectList)helper.ViewData.Model); var bindableHtml = rawHtml.ToString().Replace(compositeName, propertyName); return MvcHtmlString.Create(bindableHtml); }

    Read the article

  • RedirectToAction help: or better suggestion

    - by Dean Lunz
    Still getting my feet wet with asp.net mvc. I have a working Action and httppost action but I want to replace the "iffy" code with a RedirectToAction call because the code is rather large for what it does. A call using RedirectToAction would clean it up more. Every way I've tried it fails to work for me in that the drop down list fails to have the proper item selected. The code below works fine but calling RedirectToAction the was I have been does not work for me. So how can i rework the code below to use RedirectToAction ? I find this line of code particularly troubling because there is no garentee that the "this.Url.RequestContext.RouteData.Route" property will be of type "System.Web.Routing.Route". // get url request var urlValue = "/" + ((System.Web.Routing.Route)(this.Url.RequestContext.RouteData.Route)).Url; I also find the second piece of code rather bloated ... // build the url template urlValue = urlValue.Replace("{realm}", realm); urlValue = urlValue.Replace("{guild}", guild); urlValue = urlValue.Replace("{date}", date.ToShortDateString().Replace("/", "-")); urlValue = urlValue.Replace("{pageIndex}", pageIndex.ToString()); urlValue = urlValue.Replace("{itemCount}", itemCountToDisplay.ToString()); The route I have setup is routes.MapRoute( "GuildOverview Realm", // Route name "GuildMembers/{realm}/{guild}/{date}/{pageIndex}/{itemCount}", // URL with parameters new { controller = "GuildMembers", action = "Index" }); // Parameter defaults The code for my controller actions is below ... [HttpPost] public ActionResult Index(string realm, string guild, DateTime date, int pageIndex, int itemCount, FormCollection formCollection) { // get form data if it's there and try parse num items to display var cnt = this.Request.Form["ddlDisplayCount"]; int itemCountToDisplay = 10; if (!string.IsNullOrEmpty(cnt)) int.TryParse(cnt, out itemCountToDisplay); // get url request var urlValue = "/" + ((System.Web.Routing.Route)(this.Url.RequestContext.RouteData.Route)).Url; // build the url template urlValue = urlValue.Replace("{realm}", realm); urlValue = urlValue.Replace("{guild}", guild); urlValue = urlValue.Replace("{date}", date.ToShortDateString().Replace("/", "-")); urlValue = urlValue.Replace("{pageIndex}", pageIndex.ToString()); urlValue = urlValue.Replace("{itemCount}", itemCountToDisplay.ToString()); return this.Redirect(urlValue); } public ActionResult Index(string realm, string guild, DateTime date, int pageIndex, int itemCount) { // get the page index ViewData["pageIndex"] = pageIndex; // validate item count var pageItemCountItems = new[] { 10, 20, 50, 100 }; if (!pageItemCountItems.Contains(itemCount)) itemCount = pageItemCountItems[0]; // calc the number of pages there are var numPages = (this._repository.GetGuildMemberCount(date, realm, guild) / itemCount) + 1; this.ViewData["pageCount"] = numPages; // get url request var urlValue = "/" + ((System.Web.Routing.Route)(this.Url.RequestContext.RouteData.Route)).Url; // build the url template urlValue = urlValue.Replace("{realm}", realm); urlValue = urlValue.Replace("{guild}", guild); urlValue = urlValue.Replace("{date}", date.ToShortDateString().Replace("/", "-")); urlValue = urlValue.Replace("{pageIndex}", "{0}"); urlValue = urlValue.Replace("{itemCount}", itemCount.ToString()); // set url template ViewData["UrlTemplate"] = urlValue; // set list of items for the display count dropdown var itemCounts = new SelectList(pageItemCountItems, itemCount); ViewData["DisplayCount"] = itemCounts; return View(_repository.GetGuildCharacters(date, realm, guild, (pageIndex - 1) * itemCount, itemCount)); } and my Index view contains the fallowing <%=Html.SimplePager(int.Parse(ViewData["pageIndex"].ToString()), int.Parse(ViewData["pageCount"].ToString()), ViewData["urlTemplate"].ToString(), "nav-menu")%> <% using (Html.BeginForm()) { %> <%= Html.DropDownList("ddlDisplayCount", (SelectList)ViewData["DisplayCount"], new { onchange = "this.form.submit();" })%> <% }%>

    Read the article

  • asp.net MVC RC1 RenderPartial ViewDataDictionary

    - by Mark79
    I'm trying to pass a ViewData object from a master page to a view user control using the ViewDataDictionary. The problem is the ViewDataDictionary is not returning any values in the view user control whichever way i try it. The sample code below is using an anonymous object just for demonstration although neither this method or passing a ViewData object works. Following is the RenderPartial helper method i'm trying to use: <% Html.RenderPartial("/Views/Project/Projects.ascx", ViewData.Eval("Projects"), new ViewDataDictionary(new { Test = "Mark" })); %> and in my view user control i do the following: <%= Html.Encode(ViewData["Test"]) %> Why does this not return anything? Thanks for your help. EDIT: I'm able to pass and access the stronlgy typed model without any problems. it's the ViewDataDictionary which i'm trying to use to pass say just a single value outside of the model..

    Read the article

  • Working with partial views

    - by MrW
    Hi. I'm trying to create a page that contains a grid and searching. The issue is that I want to have a partial view for the grid and one for the searching. If doing a search, this should render the grid partial view with the new information. At the moment I need information, such as what column I'm sorting by and so on, from the grid (currently stored in viewdata), in order to do the search as I want to keep those settings. This information is only available in the grid partial though. What's the best approach of this to make it neat and nice in the code, but not a mess to work with? Where can I store information that I need in the other partial view? Partial View 1; <table> <%= Html.CreateGrid(Model, "Grid", "Grid", (int)ViewData["SortColumn"], (bool)ViewData["SortedASC"])%> </table> Partial View 2; <div class="searchControl"> <input type="text" class="SearchBox" href="<%= Url.Action("Grid", "Grid", new {page = 1, columnToSortBy=/* would like to access viewdata from partial view 1 here. */, sortASC = /* would like to access viewdata from partial view 1 here. */ } ) %>" /> <input type="submit" value="Search" class="SearchButton" /> </div> I know I might take the completely wrong approach on this, so feel free to point me in the right one! Thanks!

    Read the article

  • ASP.Net MVC Keeping action parameters between postbacks

    - by Matt
    Say I have a page that display search results. I search for stackoverflow and it returns 5000 results, 10 per page. Now I find myself doing this when building links on that page: <%=Html.ActionLink("Page 1", "Search", new { query=ViewData["query"], page etc..%> <%=Html.ActionLink("Page 2", "Search", new { query=ViewData["query"], page etc..%> <%=Html.ActionLink("Page 3", "Search", new { query=ViewData["query"], page etc..%> <%=Html.ActionLink("Next", "Search", new { query=ViewData["query"], page etc..%> I dont like this, I have to build my links with careful consideration to what was posted previously etc.. What I'd like to do is <%=Html.BuildActionLinkUsingCurrentActionPostData ("Next", "Search", new { Page = 1}); where the anonymous dictionary overrides anything currently set by previous action. Essentially I care about what the previous action parameters were, because I want to reuse, it sounds simple, but start adding sort and loads of advance search options and it starts getting messy. Im probably missing something obvious

    Read the article

  • null values from listbox, are not evaluated in the model binding of ASP.NET-MVC

    - by Jorge
    The model validation doesn't evaluates the attributes linked to listbox values if you don't select at least one of them. This way is not possible to do a model evaluation using DataAnnotations in order to inform required values. The controller: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using TestValidation.Models; namespace TestValidation.Controllers { [HandleError] public class HomeController : Controller { private SelectList list = new SelectList(new List<string>() { "Sao Paulo", "Toronto", "New York", "Vancouver" }); public ActionResult Index() { ViewData["ModelState"] = "NOT EVAL"; ViewData["ItemsList"] = list; return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(MyEntity entity) { if (ModelState.IsValid) { ViewData["ModelState"] = "VALID"; } else { ViewData["ModelState"] = "NOT VALID!!!"; } ViewData["ItemsList"] = list; return View(); } public ActionResult About() { return View(); } } } The View: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TestValidation.Models.MyEntity>" %> <asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server"> Home Page </asp:Content> <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server"> <h2> Validation Test</h2> <p> <% using (Html.BeginForm()) {%> <fieldset> <p> ModelState: <%= Html.Encode((string)ViewData["ModelState"])%> </p> <p> <label for="Name"> Name:</label> <%= Html.TextBoxFor(m => m.Name)%> <%= Html.ValidationMessageFor(m => m.Name)%> </p> <p> <label for="ItemFromList"> Items (list):</label> <%= Html.ListBoxFor(m => m.ItemFromList, ViewData["ItemsList"] as SelectList)%> <%= Html.ValidationMessageFor(m => m.ItemFromList)%> </p> <p> <label for="ItemFromCombo"> Items (combo):</label> <%= Html.DropDownListFor(m => m.ItemFromCombo, ViewData["ItemsList"] as SelectList)%> <%= Html.ValidationMessageFor(m => m.ItemFromCombo)%> </p> <p> <input type="submit" value="Submit" /> </p> </fieldset> <% } %> </asp:Content> The Model: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace TestValidation.Models { public class MyEntity_Validate : ValidationAttribute { public MyEntity_Validate() { this.ErrorMessage = "Validated!. Is <> Toronto"; } public override bool IsValid(object value) { return ((string)value == "Toronto"); } } public class MyEntity { [Required] public string Name { get; set; } [MyEntity_Validate] public string ItemFromList { get; set; } [MyEntity_Validate] public string ItemFromCombo { get; set; } } } Any help would be very much appreciated. Thank you.

    Read the article

  • Display PDF in Html

    - by anil
    Hi, i want to show PDF in a view in MVC, following function return file public ActionResult TakeoffPlans(string projID) { Highmark.BLL.Models.Project proj = GetProject(projID); List ff = proj.GetFiles(Project_Thin.Folders.CompletedTakeoff, false); ViewData["HasFile"] = "0"; if (ff != null && ff.Count 0 && ff.Where(p = p.FileExtension == "pdf").Count() 0) { ViewData["HasFile"] = "1"; } ViewData["ProjectID"] = projID; ViewData["Folder"] = Project_Thin.Folders.CompletedTakeoff; //return View("UcRenderPDF"); string fileName = Server.MapPath("~/Content/Project List Update 2.pdf"); return File(fileName, "application/pdf", Server.HtmlEncode(fileName)); } but it display some bad data in view, please help me on this

    Read the article

  • Modelbinding using Interfaces in ASP.NET MVC 2

    - by Thomas
    I have the following View Data: public class ShoppingCartViewData { public IList<IShoppingCartItem> Cart { get; set; } } I populate the viewdata in my controller: viewData.Cart = CurrentSession.CartItems; return View(viewData); And send the data to the view and display it using: <% for (int i = 0; i < Model.Cart.Count; i++ ) { %> <%= Html.TextBoxFor(m => m.Cart[i].Quantity)%> <%= Html.HiddenFor(m => m.Cart[i].Id) %> <% } %> I want to be able to catch the viewdata on the post. When I try: [HttpPost] public ActionResult UpdateCart(ShoppingCartViewData viewData) { ... } When I run this I get a: System.MissingMethodException: Cannot create an instance of an interface. Can anyone shed some light on this. What would I have to do to get this to work? Many Thanks

    Read the article

  • How to pass special characters so ASP.NET MVC can handle correctly query string data?

    - by labilbe
    Hello, I am using a route like this one: routes.MapRoute("Invoice-New-NewCustomer", "Invoice/New/Customer/New/{*name}", new { controller = "Customer", action = "NewInvoice" }, new { name = @"[^\.]*" }); There is an action which handles this route: public ActionResult NewInvoice(string name) { AddClientSideValidation(); CustomerViewData viewData = GetNewViewData(); viewData.InvoiceId = "0"; viewData.Customer.Name = name; return View("New", viewData); } When I call return RedirectToAction("NewInvoice", "Customer", new {name}); and name is equal to "The C# Guy", the "name" parameter is truncated to "The C". So my question is : What is the best way to handle this kind of special character with ASP.NET MVC? Thanks!

    Read the article

  • How do I reference members of a single object passed to the View?

    - by Juxtaposed
    I'm new to MVC2 in ASP.NET/C#, so please forgive me if I misunderstand something. I have code similar to this in my Controller: var singleInstance = new Person("John"); ViewData["myInstance"] = singleInstance; return View(); So in my view, Index.aspx, I want to be able to reference members in that object. For example, Person has a member called Name, which is set in the constructor. In the view I want to get Person.Name from what is stored in the ViewData object. Ex.: <%= ViewData["myInstance"].name %> That doesn't work. The only real workaround I've found is to do something like this: <% var thePerson = ViewData["myInstance"]; print (or whatever the method is) thePerson.Name; %> Any help would be much appreciated... This was so much easier in PHP/Zend Framework... sigh

    Read the article

  • Why does this ActionFilterAttribute not import data to the ViewModel?

    - by Tomas Lycken
    I have the following attribute public class ImportStatusAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { var model = (IHasStatus)filterContext.Controller.ViewData.Model; model.Status = (StatusMessageViewModel)filterContext.Controller.TempData["status"]; filterContext.Controller.ViewData.Model = model; } } which I test with the following test method (the first of several I'll write when this one passes...) [TestMethod] public void OnActionExecuted_ImportsStatusFromTempDataToModel() { // Arrange Expect(new { Status = new StatusMessageViewModel() { Subject = "The test", Predicate = "has been tested" }, Key = "status" }); var filterContext = new Mock<ActionExecutedContext>(); var model = new Mock<IHasStatus>(); var tempData = new TempDataDictionary(); var viewData = new ViewDataDictionary(model.Object); var controller = new FakeController() { ViewData = viewData, TempData = tempData }; tempData.Add(expected.Key, expected.Status); filterContext.Setup(c => c.Controller).Returns(controller); var attribute = new ImportStatusAttribute(); // Act attribute.OnActionExecuted(filterContext.Object); // Assert Assert.IsNotNull(model.Object.Status, "The status was not exported"); Assert.AreEqual(model.Object.Status.ToString(), ((StatusMessageViewModel)expected.Status).ToString(), "The status was not the expected"); } (Expect() is a method that saves some expectations in the expected object...) When I run the test, it fails on the first assertion, and I can't get my head around why. Debugging, I can see that model is populated correctly, and that (StatusMessageViewModel)filterContext.Controller.TempData["status"] has the correct data. But after model.Status = (StatusMessageViewModel)filterContext.Controller.TempData["status"]; model.Status is still null in my watch window. Why can't I do this?

    Read the article

  • ASP.NET MVC 3 Hosting :: New Features in ASP.NET MVC 3

    - by mbridge
    Razor View Engine The Razor view engine is a new view engine option for ASP.NET MVC that supports the Razor templating syntax. The Razor syntax is a streamlined approach to HTML templating designed with the goal of being a code driven minimalist templating approach that builds on existing C#, VB.NET and HTML knowledge. The result of this approach is that Razor views are very lean and do not contain unnecessary constructs that get in the way of you and your code. ASP.NET MVC 3 Preview 1 only supports C# Razor views which use the .cshtml file extension. VB.NET support will be enabled in later releases of ASP.NET MVC 3. For more information and examples, see Introducing “Razor” – a new view engine for ASP.NET on Scott Guthrie’s blog. Dynamic View and ViewModel Properties A new dynamic View property is available in views, which provides access to the ViewData object using a simpler syntax. For example, imagine two items are added to the ViewData dictionary in the Index controller action using code like the following: public ActionResult Index() {          ViewData["Title"] = "The Title";          ViewData["Message"] = "Hello World!"; } Those properties can be accessed in the Index view using code like this: <h2>View.Title</h2> <p>View.Message</p> There is also a new dynamic ViewModel property in the Controller class that lets you add items to the ViewData dictionary using a simpler syntax. Using the previous controller example, the two values added to the ViewData dictionary can be rewritten using the following code: public ActionResult Index() {     ViewModel.Title = "The Title";     ViewModel.Message = "Hello World!"; } “Add View” Dialog Box Supports Multiple View Engines The Add View dialog box in Visual Studio includes extensibility hooks that allow it to support multiple view engines, as shown in the following figure: Service Location and Dependency Injection Support ASP.NET MVC 3 introduces improved support for applying Dependency Injection (DI) via Inversion of Control (IoC) containers. ASP.NET MVC 3 Preview 1 provides the following hooks for locating services and injecting dependencies: - Creating controller factories. - Creating controllers and setting dependencies. - Setting dependencies on view pages for both the Web Form view engine and the Razor view engine (for types that derive from ViewPage, ViewUserControl, ViewMasterPage, WebViewPage). - Setting dependencies on action filters. Using a Dependency Injection container is not required in order for ASP.NET MVC 3 to function properly. Global Filters ASP.NET MVC 3 allows you to register filters that apply globally to all controller action methods. Adding a filter to the global filters collection ensures that the filter runs for all controller requests. To register an action filter globally, you can make the following call in the Application_Start method in the Global.asax file: GlobalFilters.Filters.Add(new MyActionFilter()); The source of global action filters is abstracted by the new IFilterProvider interface, which can be registered manually or by using Dependency Injection. This allows you to provide your own source of action filters and choose at run time whether to apply a filter to an action in a particular request. New JsonValueProviderFactory Class The new JsonValueProviderFactory class allows action methods to receive JSON-encoded data and model-bind it to an action-method parameter. This is useful in scenarios such as client templating. Client templates enable you to format and display a single data item or set of data items by using a fragment of HTML. ASP.NET MVC 3 lets you connect client templates easily with an action method that both returns and receives JSON data. Support for .NET Framework 4 Validation Attributes and IvalidatableObject The ValidationAttribute class was improved in the .NET Framework 4 to enable richer support for validation. When you write a custom validation attribute, you can use a new IsValid overload that provides a ValidationContext instance. This instance provides information about the current validation context, such as what object is being validated. This change enables scenarios such as validating the current value based on another property of the model. The following example shows a sample custom attribute that ensures that the value of PropertyOne is always larger than the value of PropertyTwo: public class CompareValidationAttribute : ValidationAttribute {     protected override ValidationResult IsValid(object value,              ValidationContext validationContext) {         var model = validationContext.ObjectInstance as SomeModel;         if (model.PropertyOne > model.PropertyTwo) {            return ValidationResult.Success;         }         return new ValidationResult("PropertyOne must be larger than PropertyTwo");     } } Validation in ASP.NET MVC also supports the .NET Framework 4 IValidatableObject interface. This interface allows your model to perform model-level validation, as in the following example: public class SomeModel : IValidatableObject {     public int PropertyOne { get; set; }     public int PropertyTwo { get; set; }     public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {         if (PropertyOne <= PropertyTwo) {            yield return new ValidationResult(                "PropertyOne must be larger than PropertyTwo");         }     } } New IClientValidatable Interface The new IClientValidatable interface allows the validation framework to discover at run time whether a validator has support for client validation. This interface is designed to be independent of the underlying implementation; therefore, where you implement the interface depends on the validation framework in use. For example, for the default data annotations-based validator, the interface would be applied on the validation attribute. Support for .NET Framework 4 Metadata Attributes ASP.NET MVC 3 now supports .NET Framework 4 metadata attributes such as DisplayAttribute. New IMetadataAware Interface The new IMetadataAware interface allows you to write attributes that simplify how you can contribute to the ModelMetadata creation process. Before this interface was available, you needed to write a custom metadata provider in order to have an attribute provide extra metadata. This interface is consumed by the AssociatedMetadataProvider class, so support for the IMetadataAware interface is automatically inherited by all classes that derive from that class (notably, the DataAnnotationsModelMetadataProvider class). New Action Result Types In ASP.NET MVC 3, the Controller class includes two new action result types and corresponding helper methods. HttpNotFoundResult Action The new HttpNotFoundResult action result is used to indicate that a resource requested by the current URL was not found. The status code is 404. This class derives from HttpStatusCodeResult. The Controller class includes an HttpNotFound method that returns an instance of this action result type, as shown in the following example: public ActionResult List(int id) {     if (id < 0) {                 return HttpNotFound();     }     return View(); } HttpStatusCodeResult Action The new HttpStatusCodeResult action result is used to set the response status code and description. Permanent Redirect The HttpRedirectResult class has a new Boolean Permanent property that is used to indicate whether a permanent redirect should occur. A permanent redirect uses the HTTP 301 status code. Corresponding to this change, the Controller class now has several methods for performing permanent redirects: - RedirectPermanent - RedirectToRoutePermanent - RedirectToActionPermanent These methods return an instance of HttpRedirectResult with the Permanent property set to true. Breaking Changes The order of execution for exception filters has changed for exception filters that have the same Order value. In ASP.NET MVC 2 and earlier, exception filters on the controller with the same Order as those on an action method were executed before the exception filters on the action method. This would typically be the case when exception filters were applied without a specified order Order value. In MVC 3, this order has been reversed in order to allow the most specific exception handler to execute first. As in earlier versions, if the Order property is explicitly specified, the filters are run in the specified order. Known Issues When you are editing a Razor view (CSHTML file), the Go To Controller menu item in Visual Studio will not be available, and there are no code snippets.

    Read the article

  • ASP.NET MVC 2 strange behavior

    - by Voice
    Hi Recently I installed VS 2010 Release (migrated from RC) and my MVC application is not working anymore. More concrete: I have a wizard with several steps for new customer account creation (Jquery form wizard, but it doesn't really matter). Each step contains a typed partial View for each part of account: Company, Customer, Licence, etc. When I submit the form I see really strange thing in ModelState. There are duplicate keys for Company: with "Company" prefix and without it. Something like this: [6] "Company.Phone" string [12] "Phone" string My model state for all these keys is not valid because Company is actually null and validation fails. When it was RC there were no such keys with "Company" prefix. So these keys in ModelState with prefix "Company" appeared after I installed VS Release. Here is my code: Main View <div id="registerSteps"> <div id="firstStep" class="step"> <fieldset> <legend><%=Html.Encode(Register.CustomerInfo) %></legend> <% Html.RenderPartial("CustomerInfo", ViewData["newCust"]); %> </fieldset> </div> <div id="secondStep" class="step"> <fieldset> <legend><%=Html.Encode(Register.CompanyInfo) %></legend> <% Html.RenderPartial("CompanyInfo", ViewData["newComp"]); %> </fieldset> </div> <div id="thirdStep" class="step"> <fieldset> <legend><%=Html.Encode(Register.LicenceInfo) %></legend> <% Html.RenderPartial("LicenceInfo", ViewData["newLic"]); %> </fieldset> </div> <div id="lastStep" class="step"> <fieldset> <legend><%=Html.Encode(Register.PrivacyStatement) %></legend> <% Html.RenderPartial("PrivacyStatementInfo"); %> </fieldset> </div> <div id="registerNavigation"> <input class="navigation_button" value="Back" type="reset"/> <input class="navigation_button" value="Next" type="submit"/> </div> </div> Two partial views (to show that they are actually identical): Company: <div id="dCompanyInfo"> <div> <div> <%=Html.LocalizableLabelFor(company => company.Name, Register.CompanyName) %> </div> <div> <%=Html.TextBoxFor(company => company.Name) %> <%=Html.ValidationMessageFor(company => company.Name) %> </div> </div> <div> <div> <%=Html.LocalizableLabelFor(company => company.Phone, Register.Phone) %> </div> <div> <%=Html.TextBoxFor(company => company.Phone) %> <%=Html.ValidationMessageFor(company => company.Phone) %> </div> </div> <div> <div> <%=Html.LocalizableLabelFor(company => company.Fax, Register.Fax) %> </div> <div> <%=Html.TextBoxFor(company => company.Fax) %> <%=Html.ValidationMessageFor(company => company.Fax) %> </div> </div> <div> <div> <%=Html.LocalizableLabelFor(company => company.Size_ID, Register.CompanySize) %> </div> <div> <%=Html.ValueListDropDown(company => company.Size_ID, (CodeRoad.AQua.DomainModel.ValueList)ViewData["CompSize"], (string)ViewData["Culture"]) %> <%=Html.ValidationMessageFor(company => company.Size_ID) %> </div> </div> <div> <div> <%=Html.LocalizableLabelFor(company => company.Industry_ID, Register.Industry) %> </div> <div> <%=Html.ValueListDropDown(company => company.Industry_ID, (CodeRoad.AQua.DomainModel.ValueList)ViewData["Industry"], (string)ViewData["Culture"]) %> <%=Html.ValidationMessageFor(company => company.Industry_ID) %> </div> </div> </div> And for Customer <div id="dCustomerInfo"> <div> <div> <%=Html.LocalizableLabelFor(customer => customer.Email, Register.Email) %> </div> <div> <%=Html.TextBoxFor(customer => customer.Email) %> <%=Html.ValidationMessageFor(customer => customer.Email) %> </div> </div> <div> <div> <%=Html.LocalizableLabelFor(customer => customer.Male, Register.Gender) %> </div> <div> <%=Html.ListBoolEditor(customer => customer.Male, Register.Male, Register.Female, Register.GenderOptionLabel) %> <%=Html.ValidationMessageFor(customer => customer.Male) %> </div> </div> <div> <div> <%=Html.LocalizableLabelFor(customer => customer.FirstName, Register.FirstName) %> </div> <div> <%=Html.TextBoxFor(customer => customer.FirstName) %> <%=Html.ValidationMessageFor(customer => customer.FirstName) %> </div> </div> <div> <div> <%=Html.LocalizableLabelFor(customer => customer.LastName, Register.LastName) %> </div> <div> <%=Html.TextBoxFor(customer => customer.LastName) %> <%=Html.ValidationMessageFor(customer => customer.LastName) %> </div> </div> <div> <div> <%=Html.LocalizableLabelFor(customer => customer.Role_ID, Register.Role) %> </div> <div> <%=Html.ValueListDropDown(customer => customer.Role_ID, (CodeRoad.AQua.DomainModel.ValueList)ViewData["OrgRole"], (string)ViewData["Culture"]) %> <%=Html.ValidationMessageFor(customer => customer.Role_ID) %> </div> </div> </div> There are some home made extension methods, but they worked pretty well in previous version (VS RC). Html which is generated is also ok, no "Company.Phone"-like stuff. So I wonder, where all these keys with "Company" came from and what can I do with that? I appreciate any solution.

    Read the article

  • Asp.net MVC jquery-ajax dont render html

    - by Troublesum
    Hi, Im trying to use jqeury ajax with MVC i can get it to post back to the action i want and it returns the ViewData objects with updated Data but never renders the HTML. I have i View which contains some MVC User Controls and i want them to update on a timer. Here is my View Markup <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/PageWithSummaryViewAndTabs.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="FullCaseTitle" ContentPlaceHolderID="TitleContent" runat="server"> </asp:Content> <asp:Content ID="FullCaseContent" ContentPlaceHolderID="MainContent" runat="server"> <script type="text/javascript"> window.setInterval(test, 5000); function test() { jQuery.get("/PatientCase/RefreshEPRF", function(response) { }); } </script> <div id="loadingDiv" style="display:none">Updating</div> <input id="refreshPatientCaseIndexButton" type="submit" visible="true" title="refresh" value="Refresh" /> <h2>Full Case</h2> <div id="EPRFContent"> <%Html.RenderPartial(@"~/Views/PatientCase/SectionEPRF.ascx"); %> <%Html.RenderPartial(@"~/Views/PatientCase/SectionDrugs.ascx"); %> </div> <div id="ImageContent"> <%Html.RenderPartial(@"~/Views/PatientCase/SectionImagery.ascx"); % On postback i call a Action Called RefreshEPRF which loads just the required user controls again <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <%Html.RenderPartial(@"~/Views/PatientCase/SectionEPRF.ascx"); %> <%Html.RenderPartial(@"~/Views/PatientCase/SectionDrugs.ascx"); %> And finaly the marpup in the control <table id="detailstable"> <tr><td id="detailslablecolumn">Patient Name : </td><td> <% foreach (var item in (List<STS_Lite.Models.PatinetCase.EPRFItem>)ViewData["EPRF"]) { if (item.datumItemId == 46) { if (item.Stroke) { %> <img src="/PatientCaseIndex/InkImageData/GetInkImage/<%=ViewData["PatientCaseId"]%>/<%=ViewData["TemplateInstanceId"]%>/<%=item.TemplateItemId %>" /> <% } else {%> <%=item.Value.ToString()%> <%} break; } } %></td></tr><table> When i step through this code the ViewData in the user control has the new updated values but the page comes back with no new values. I have tried the jquery.get and ajax but with no luck. Any help would be great thanks

    Read the article

  • ASP.NET MVC for the php/asp noob

    - by dotjosh
    I was talking to a friend today, who's foremost a php developer, about his thoughts on Umbraco and he said "Well they're apparently working feverishly on the new version of Umbraco, which will be MVC... which i still don't know what that means, but I know you like it." I ended up giving him a ground up explanation of ASP.NET MVC, so I'm posting this so he can link this to his friends and for anyone else who finds it useful.  The whole goal was to be as simple as possible, not being focused on proper syntax. Model-View-Controller (or MVC) is just a pattern that is used for handling UI interaction with your backend.  In a typical web app, you can imagine the *M*odel as your database model, the *V*iew as your HTML page, and the *C*ontroller as the class inbetween.  MVC handles your web request different than your typical php/asp app.In your php/asp app, your url maps directly to a php/asp file that contains html, mixed with database access code and redirects.In an MVC app, your url route is mapped to a method on a class (the controller).  The body of this method can do some database access and THEN decide which *V*iew (html/aspx page) should be displayed;  putting the controller in charge and not the view... a clear seperation of concerns that provides better reusibility and generally promotes cleaner code. Mysite.com, a quick example:Let's say you hit the following url in your application: http://www.mysite.com/Product/ShowItem?Id=4 To avoid tedious configuration, MVC uses a lot of conventions by default. For instance, the above url in your app would automatically make MVC search for a .net class with the name "Product" and a method named "ShowItem" based on the pattern of the url.  So if you name things properly, your method would automatically be called when you entered the above url.  Additionally, it would automatically map/hydrate the "int id" parameter that was in your querystring, matched by name.Product.cspublic class Product : Controller{    public ViewResult ShowItem(int id)    {        return View();    }} From this point you can write the code in the body of this method to do some database access and then pass a "bag" (also known as the ViewData) of data to your chosen *V*iew (html page) to use for display.  The view(html) ONLY needs to be worried about displaying the flattened data that it's been given in the best way it can;  this allows the view to be reused throughout your application as *just* a view, and not be coupled to HOW the data for that view get's loaded.. Product.cspublic class Product : Controller{    public ViewResult ShowItem(int id)    {        var database = new Database();        var item = database.GetItem(id);        ViewData["TheItem"] = item;        return View();    }} Again by convention, since the class' method name is "ShowItem", it'll search for a view named "ShowItem.aspx" by default, and pass the ViewData bag to it to use. ShowItem.aspx<html>     <body>      <%        var item =(Item)ViewData["TheItem"]       %>       <h1><%= item.FullProductName %></h1>     </body></html> BUT WAIT! WHY DOES MICROSOFT HAVE TO DO THINGS SO DIFFERENTLY!?They aren't... here are some other frameworks you may have heard of that use the same pattern in a their own way: Ruby On Rails Grails Spring MVC Struts Django    

    Read the article

  • BinaryWrite exception "OutputStream is not available when a custom TextWriter is used" in MVC 2 ASP.

    - by Grant
    Hi, I have a view rendering a stream using the response BinaryWrite method. This all worked fine under ASP.NET 4 using the Beta 2 but throws this exception in the RC release: "HttpException" , "OutputStream is not available when a custom TextWriter is used." <%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %> <%@ Import Namespace="System.IO" %> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { if (ViewData["Error"] == null) { Response.Buffer = true; Response.Clear(); Response.ContentType = ViewData["DocType"] as string; Response.AddHeader("content-disposition", ViewData["Disposition"] as string); Response.CacheControl = "No-cache"; MemoryStream stream = ViewData["DocAsStream"] as MemoryStream; Response.BinaryWrite(stream.ToArray()); Response.Flush(); Response.Close(); } } </script> </script> The view is generated from a client side redirect (jquery replace location call in the previous page using Url.Action helper to render the link of course). This is all in an iframe. Anyone have an idea why this occurs?

    Read the article

  • What is the difference (if any) between Html.Partial(view, model) and Html.RenderPartial(view,model)

    - by Stephane
    Other than the type it returns and the fact that you call it differently of course <% Html.RenderPartial(...); %> <%= Html.Partial(...) %> If they are different, why would you call one rather than the other one? The definitions: // Type: System.Web.Mvc.Html.RenderPartialExtensions // Assembly: System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 // Assembly location: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 2\Assemblies\System.Web.Mvc.dll using System.Web.Mvc; namespace System.Web.Mvc.Html { public static class RenderPartialExtensions { public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName); public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData); public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model); public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData); } } // Type: System.Web.Mvc.Html.PartialExtensions // Assembly: System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 // Assembly location: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 2\Assemblies\System.Web.Mvc.dll using System.Web.Mvc; namespace System.Web.Mvc.Html { public static class PartialExtensions { public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName); public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData); public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model); public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData); } }

    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

  • Properly registering JavaScript and CSS in MVC 2 Editor Templates

    - by Jaxidian
    How do I properly register javascript blocks in an ASP.NET MVC 2 (RTM) Editor template? The specific scenario I'm in is that I want to use Dynarch JSCal2 DateTimePicker for my standard datetime picker, but this question is in general to any reusable javascript package. I have my template working properly now but it has my JS and CSS includes in my master page and I would rather only include these things if I actually need them: <link rel="stylesheet" type="text/css" href="../../Content/JSCal2-1.7/jscal2.css" /> <link rel="stylesheet" type="text/css" href="../../Content/JSCal2-1.7/border-radius.css" /> <script type="text/javascript" src="../../Scripts/JSCal2-1.7/jscal2.js"></script> <script type="text/javascript" src="../../Scripts/JSCal2-1.7/lang/en.js"></script> So obviously I could just put these lines into my template, but then if I have a screen that has 5 DateTimePickers, then this content would be duplicated 5 times which wouldn't be ideal. Anyways, I still want my View's Template to trigger this code being put into the <head> of my page. While it is completely unrelated to my asking this question, I thought I'd share my template on here (so far) in case it's useful in any way: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime>" %> <%= Html.TextBoxFor(model => Model) %> <input type="button" id="<%= ViewData.TemplateInfo.GetFullHtmlFieldId("cal-trigger") %>" value="..." /> <script type="text/javascript"> var <%= ViewData.TemplateInfo.GetFullHtmlFieldId("cal") %> = Calendar.setup({ trigger : "<%= ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty) %>", inputField : "<%= ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty) %>", onSelect : function() { this.hide(); }, showTime : 12, selectionType : Calendar.SEL_SINGLE, dateFormat : '%o/%e/%Y %l:%M %P' }); </script>

    Read the article

  • How to unit test this simple ASP.NET MVC controller

    - by Frank Schwieterman
    Lets say I have a simple controller for ASP.NET MVC I want to test. I want to test that a controller action (Foo, in this case) simply returns a link to another action (Bar, in this case). How would you test this? (either the first or second link) My implementation has the same link twice. One passes the url throw ViewData[]. This seems more testable to me, as I can check the ViewData collection returned from Foo(). Even this way though, I don't know how to validate the url itself without making dependencies on routing. The controller: public class TestController : Controller { public ActionResult Foo() { ViewData["Link2"] = Url.Action("Bar"); return View("Foo"); } public ActionResult Bar() { return View("Bar"); } } the "Foo" view: <%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" MasterPageFile="~/Views/Shared/Site.Master"%> <asp:Content ContentPlaceHolderID="MainContent" runat="server"> <%= Html.ActionLink("link 1", "Bar") %> <a href="<%= ViewData["Link2"]%>">link 2</a> </asp:Content>

    Read the article

  • Html.ListBox() and MultiselectList

    - by Ivan90
    Hi guys, I've a little problem with an Html.ListBox! I am developing a personal blog in ASP.NET MVC 1.0 and I created an adminpanel where I can add and edit a post! During this two operations, I can add also tags! I think of use an Html.ListBox() helper to list all tags, and so I can select multiple tags to add in a post! The problem isn't during the add mode, but in the edit mode, where I have to pre-select post's tags! I read that I have to use a MultiSelectList and so in its constructor pass, tags' list and tag's list(pre-selected value). But I don't know how to use this class! I post, some code: This is my models method that get all list tags in selectlist public IEnumerable<SelectListItem> GetTagsListBox() { return from t in db.Tags orderby t.IDTag descending select new SelectListItem { Text = t.TagName, Value = t.IDTag.ToString(), }; } So in Edit (Get and Post), Add(Get and Post) I use a ViewData to pass this list in Html.ListBox(). ViewData["Tags"] = tagdb.GetTagsListBox(); And in my view <%=Html.ListBox("Tags",ViewData["Tags"] as SelectList) %> So with this code it's ok in Add Mode! But in Edit Mode I need to pre-select those values! So Now, of course I have to create a method that get all tagsbypostid! and then in ViewData what Must I to pass? Any suggest?

    Read the article

  • Beginner MVC question - Correct approach to render out a List and details?

    - by fizzer
    I'm trying to set up a page where I display a list of items and the details of the selected item. I have it working but wonder whether I have followed the correct approach. I'll use customers as an example I have set the aspx page to inherit from an IEnumerable of Customers. This seems to be the standard approach to display the list of items. For the Details I have added a Customer user control which inherits from customer. I think i'm on the right track so far but I was a bit confused as to where I should store the id of the customer whose details I intend to display. I wanted to make the id optional in the controller action so that the page could be hit using "/customers" or "customers/1" so I made the arg optional and stored the id in the ViewData like this: public ActionResult Customers(string id = "0") { Models.DBContext db = new Models.DBContext(); var cList = db.Customers.OrderByDescending(c => c.CustomerNumber); if (id == "0") { ViewData["CustomerNumber"] = cList.First().CustomerNumber.ToString(); } else { ViewData["CustomerNumber"] = id; } return View("Customers", cList); } I then rendered the User control using RenderPartial in the front end: <%var CustomerList = from x in Model where x.CustomerNumber == Convert.ToInt32(ViewData["CustomerNumber"]) select x; Customer c = (Customer)CustomerList.First(); %> <% Html.RenderPartial("Customer",c); %> Then I just have an actionLink on each listed item: <%: Html.ActionLink("Select", "Customers", new { id = item.CustomerNumber })% It all seems to work but as MVC is new to me I would just be interested in others thoughts on whether this is a good approach?

    Read the article

  • MVC2 EditorTemplate for DropDownList

    - by tschreck
    I've spent the majority of the past week knee deep in the new templating functionality baked into MVC2. I had a hard time trying to get a DropDownList template working. The biggest problem I've been working to solve is how to get the source data for the drop down list to the template. I saw a lot of examples where you can put the source data in the ViewData dictionary (ViewData["DropDownSourceValuesKey"]) then retrieve them in the template itself (var sourceValues = ViewData["DropDownSourceValuesKey"];) This works, but I did not like having a silly string as the lynch pin for making this work. Below is an approach I've come up with and wanted to get opinions on this approach: here are my design goals: The view model should contain the source data for the drop down list Limit Silly Strings Not use ViewData dictionary Controller is responsible for filling the property with the source data for the drop down list Here's my View Model: public class CustomerViewModel { [ScaffoldColumn(false)] public String CustomerCode{ get; set; } [UIHint("DropDownList")] [DropDownList(DropDownListTargetProperty = "CustomerCode"] [DisplayName("Customer Code")] public IEnumerable<SelectListItem> CustomerCodeList { get; set; } public String FirstName { get; set; } public String LastName { get; set; } public String PhoneNumber { get; set; } public String Address1 { get; set; } public String Address2 { get; set; } public String City { get; set; } public String State { get; set; } public String Zip { get; set; } } My View Model has a CustomerCode property which is a value that the user selects from a list of values. I have a CustomerCodeList property that is a list of possible CustomerCode values and is the source for a drop down list. I've created a DropDownList attribute with a DropDownListTargetProperty. DropDownListTargetProperty points to the property which will be populated based on the user selection from the generated drop down (in this case, the CustomerCode property). Notice that the CustomerCode property has [ScaffoldColumn(false)] which forces the generator to skip the field in the generated output. My DropDownList.ascx file will generate a dropdown list form element with the source data from the CustomerCodeList property. The generated dropdown list will use the value of the DropDownListTargetProperty from the DropDownList attribute as the Id and the Name attributes of the Select form element. So the generated code will look like this: <select id="CustomerCode" name="CustomerCode"> <option>... </select> This works out great because when the form is submitted, MVC will populate the target property with the selected value from the drop down list because the name of the generated dropdown list IS the target property. I kinda visualize it as the CustomerCodeList property is an extension of sorts of the CustomerCode property. I've coupled the source data to the property. Here's my code for the controller: public ActionResult Create() { //retrieve CustomerCodes from a datasource of your choosing List<CustomerCode> customerCodeList = modelService.GetCustomerCodeList(); CustomerViewModel viewModel= new CustomerViewModel(); viewModel.CustomerCodeList = customerCodeList.Select(s => new SelectListItem() { Text = s.CustomerCode, Value = s.CustomerCode, Selected = (s.CustomerCode == viewModel.CustomerCode) }).AsEnumerable(); return View(viewModel); } Here's my code for the DropDownListAttribute: namespace AutoForm.Attributes { public class DropDownListAttribute : Attribute { public String DropDownListTargetProperty { get; set; } } } Here's my code for the template (DropDownList.ascx): <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<SelectListItem>>" %> <%@ Import Namespace="AutoForm.Attributes"%> <script runat="server"> DropDownListAttribute GetDropDownListAttribute() { var dropDownListAttribute = new DropDownListAttribute(); if (ViewData.ModelMetadata.AdditionalValues.ContainsKey("DropDownListAttribute")) { dropDownListAttribute = (DropDownListAttribute)ViewData.ModelMetadata.AdditionalValues["DropDownListAttribute"]; } return dropDownListAttribute; } </script> <% DropDownListAttribute attribute = GetDropDownListAttribute();%> <select id="<%= attribute.DropDownListTargetProperty %>" name="<%= attribute.DropDownListTargetProperty %>"> <% foreach(SelectListItem item in ViewData.Model) {%> <% if (item.Selected == true) {%> <option value="<%= item.Value %>" selected="true"><%= item.Text %></option> <% } %> <% else {%> <option value="<%= item.Value %>"><%= item.Text %></option> <% } %> <% } %> </select> I tried using the Html.DropDownList helper, but it would not allow me to change the Id and Name attributes of the generated Select element. NOTE: you have to override the CreateMetadata method of the DataAnnotationsModelMetadataProvider for the DropDownListAttribute. Here's the code for that: public class MetadataProvider : DataAnnotationsModelMetadataProvider { protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) { var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName); var additionalValues = attributes.OfType<DropDownListAttribute>().FirstOrDefault(); if (additionalValues != null) { metadata.AdditionalValues.Add("DropDownListAttribute", additionalValues); } return metadata; } } Then you have to make a call to the new MetadataProvider in Application_Start of Global.asax.cs: protected void Application_Start() { RegisterRoutes(RouteTable.Routes); ModelMetadataProviders.Current = new MetadataProvider(); } Well, I hope this makes sense and I hope this approach may save you some time. I'd like some feedback on this approach please. Is there a better approach?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >