Search Results

Search found 102 results on 5 pages for 'viewusercontrol'.

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

  • How do I encapsulate form/post/validation[/redirect] in ViewUserControl in ASP.Net MVC 2

    - by paul
    What I am trying to achieve: encapsulate a Login (or any) Form to be reused across site post to self when Login/validation fails, show original page with Validation Summary (some might argue to just post to Login Page and show Validation Summary there; if what I'm trying to achieve isn't possible, I will just go that route) when Login succeeds, redirect to /App/Home/Index also, want to: stick to PRG principles avoid ajax keep Login Form (UserController.Login()) as encapsulated as possible; avoid having to implement HomeController.Login() since the Login Form might appear elsewhere All but the redirect works. My approach thus far has been: Home/Index includes Login Form: <%Html.RenderAction("Login","User");%> User/Login ViewUserControl<UserLoginViewModel> includes: <%=Html.ValidationSummary("") % using(Html.BeginForm()){} includes hidden form field "userlogin"="1" public class UserController : BaseController { ... [AcceptPostWhenFieldExists(FieldName = "userlogin")] public ActionResult Login(UserLoginViewModel model, FormCollection form){ if (ModelState.IsValid) { if(checkUserCredentials()) { setUserCredentials() return this.RedirectToAction<Areas.App.Controllers.HomeController>(x = x.Index()); } else { return View(); } } ... } Works great when: ModelState or User Credentials fail -- return View() does yield to Home/Index and displays appropriate validation summary. (I have a Register Form on the same page, using the same structure. Each form's validation summary only shows when that form is submitted.) Fails when: ModelState and User Credentials valid -- RedirectToAction<>() gives following error: "Child actions are not allowed to perform redirect actions." It seems like in the Classic ASP days, this would've been solved with Response.Buffer=True. Is there an equivalent setting or workaround now? Btw, running: ASP.Net 4, MVC 2, VS 2010, Dev/Debugging Web Server I hope all of that makes sense. So, what are my options? Or where am I going wrong in my approach? tia!

    Read the article

  • Add property to an ASP.NET MVC 2 ViewUserControl

    - by roosteronacid
    I have created a ViewUserControl in my ASP.NET MVC 2 project. This ViewUserControl serves as the general page-header for all views in the project. How can I add a custom property on ViewUserControls, accessible from views using that control?..: <%@ Register Src="../Shared/Header.ascx" TagName="Header" TagPrefix="uc" %> <uc:Header runat="server" ID="ucHeader" MenuItemHighlighted="Menuitem.FrontPage" /> <!-- custom property, here -->

    Read the article

  • How to check if returning View is of type PartialViewResult or a ViewUserControl

    - by mare
    In the method FindView() I have to somehow check if the View we are requesting is a ViewUserControl. Because otherwise I get an error saying: "A master name cannot be specified when the view is a ViewUserControl." This is my custom view engine code right now: public class PendingViewEngine : VirtualPathProviderViewEngine { public PendingViewEngine() { // This is where we tell MVC where to look for our files. /* {0} = view name or master page name * {1} = controller name */ MasterLocationFormats = new[] {"~/Views/Shared/{0}.master", "~/Views/{0}.master"}; ViewLocationFormats = new[] { "~/Views/{1}/{0}.aspx", "~/Views/Shared/{0}.aspx", "~/Views/Shared/{0}.ascx", "~/Views/{1}/{0}.ascx" }; PartialViewLocationFormats = new[] {"~/Views/{1}/{0}.ascx", "~/Views/Shared/{0}.ascx"}; } protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) { return new WebFormView(partialPath, ""); } protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) { return new WebFormView(viewPath, masterPath); // this line produces the error because we cannot set master page on ASCXs, so I need an "if" here } public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) { if (controllerContext.HttpContext.Request.IsAjaxRequest()) return base.FindView(controllerContext, viewName, "Modal", useCache); return base.FindView(controllerContext, viewName, "Site", useCache); } } The above ViewEngine fails on calls like this: <% Html.RenderAction("Display", "MyController", new { zoneslug = "some-zone-slug" });%> The action I am rendering here is this: public ActionResult Display(string zoneslug) { WidgetZone zone; if (!_repository.IsUniqueSlug(zoneslug)) zone = (WidgetZone) _repository.GetInstance(zoneslug); else { // do something here } // WidgetZone used here is WidgetZone.ascx, so a partial return View("WidgetZone", zone); } I cannot use RenderPartial because you cannot send route values to RenderPartial the way you can to RenderAction. To my knowledge there is no way to provide RouteValueDictionary to RenderPartial() like the way you can to RenderAction().

    Read the article

  • Rendering a derived partial view with Html.RenderPartial

    - by FreshCode
    Calling Html.RenderPartial("~/Views/Payments/MyControl.ascx"); from a view works if Method.ascx is a control that directly inherits System.Web.Mvc.ViewUserControl. However, if the control inherits a new class that derives from System.Web.Mvc.ViewUserControl, the call to Html.RenderPartial("~/Views/Payments/MyDerivedControl.ascx"); fails, reporting that no such view exists. Example derived ViewUserControl: class MyDerivedControl : System.Web.Mvc.ViewUserControl { public Method() { ViewData["SomeData"] = "test"; } } Is there a workaround, or is there another way I should be doing this? Perhaps an HTML helper?

    Read the article

  • Could not load type 'System.Web.Mvc.ViewUserControl<SOMETYPE>'.

    - by Evgenyt
    I'm trying to deploy ASP.NET MVC 2 project (VS2010) to Win Server 2008 R2 It works perfectly on dev machine. But strange error occurs at Server 2008 R2: When .ascx file has header that uses generic type: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyProj.Web.Models.RangeViewModel>" %> Server reports Could not load type 'System.Web.Mvc.ViewUserControl<MyProj.Web.Models.RangeViewModel>'. But when I declare somewhere in .cs file type like public class AA : System.Web.Mvc.ViewUserControl<MyProj.Web.Models.RangeViewModel> { } and use it instead in <%@ Control header. Then it works as it should. Am I missing something?

    Read the article

  • Asp.Net MVC2 Clientside Validation problem with controls with prefixes

    - by alexander
    The problem is: when I put 2 controls of the same type on a page I need to specify different prefixes for binding. In this case the validation rules generated right after the form are incorrect. So how to get client validation work for the case?: the page contains: <% Html.RenderPartial(ViewLocations.Shared.PhoneEditPartial, new PhoneViewModel { Phone = person.PhonePhone, Prefix = "PhonePhone" }); Html.RenderPartial(ViewLocations.Shared.PhoneEditPartial, new PhoneViewModel { Phone = person.FaxPhone, Prefix = "FaxPhone" }); %> the control ViewUserControl<PhoneViewModel>: <%= Html.TextBox(Model.GetPrefixed("CountryCode"), Model.Phone.CountryCode) %> <%= Html.ValidationMessage("Phone.CountryCode", new { id = Model.GetPrefixed("CountryCode"), name = Model.GetPrefixed("CountryCode") })%> where Model.GetPrefixed("CountryCode") just returns "FaxPhone.CountryCode" or "PhonePhone.CountryCode" depending on prefix And here is the validation rules generated after the form. They are duplicated for the field name "Phone.CountryCode". While the desired result is 2 rules (required, number) for each of the FieldNames "FaxPhone.CountryCode", "PhonePhone.CountryCode" The question is somewhat duplicate of http://stackoverflow.com/questions/2675606/asp-net-mvc2-clientside-validation-and-duplicate-ids-problem but the advise to manually generate ids doesn't helps.

    Read the article

  • ASP.NET MVC Strongly Typed Partial View, gives could not load type error

    - by Matt
    I am attempting to create a strongly typed view with a "MVC View User Control" that is being rendered using Html.RenderPartial(). The top of my ascx file looks like this: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Collections.IEnumerable<string>>" %> There is nothing else on this page, currently. When I execute the app and load the page that renders this control, I get the following error: Could not load type 'System.Web.Mvc.ViewUserControl<System.Collections.IEnumerable<string>>'. So, then I simplified it: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<String>" %> And then, just in case it needed to be fully qualified: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.String>" %> Everytime I get the same error (substituting type). what am I doing wrong here? I'm on .NET 3.5 with ASP.NET MVC 1.0 RTM.

    Read the article

  • ASP.NET 1.0 site error after upgrade to VS.NET 2010

    - by Keith
    Help. I installed VS.NET 2010 and now my existing ASP.NET MVC application won't run. I checked that the 1.0 version of System.Web.Mvc is still referenced but when I browse my application, I get an error like this: "Compiler Error Message: CS1579: foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'". My partial view has this declaration: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<ProductModel" %> //various import statements <div <% foreach (var category in Model.Categories) { % <span<%= category.Name %</span <span<%= category.Market%</span <% } % </div For what it's worth, the source view shows ViewUserControl in red and gives a tool tip reading "Cannot resolve symbol 'ViewUserControl'". My working code didn't change, the only delta is that I upgraded to VS.NET 2010 (which includes MVC 2.0); I'm sure something is not referenced correctly but I cannot figure out what's going on.

    Read the article

  • Getting the error "The view at '~/Views/Page/home.aspx' must derive from ViewPage, ViewPage<TViewDat

    - by Glenn Slaven
    I've just installed MVC2 and I've got a view that looks like this <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Home.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Home </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Home</h2> </asp:Content> And the controller is just returning the view. But when I run the page I get this error: System.InvalidOperationException: The view at '~/Views/Page/home.aspx' must derive from ViewPage, ViewPage, ViewUserControl, or ViewUserControl.

    Read the article

  • Trying to pass Model down to partial, how do I do this?

    - by mrblah
    My action creates a strongly typed viewdata, which is passed to my view. In the view, I pass the Model to the render partial method. public ActionResult Index() { ViewDataForIndex vd = new ViewDataForIndex(); vd.Users = Users.GetAll(); return View(vd); } public class ViewDataForIndex: ViewData { public IList<User> Users {get;set;} } now in the view: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ViewDataForIndex>" %> <% Html.RenderPartial("~/controls/blah.ascx", ViewData.Model); %> and in blah.ascx: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> how do I access my model now? if I wanted to create a strongly typed class for my ViewUserControl, how would I do that? inherit from?

    Read the article

  • Render label for a field inside ASP.NET MVC 2 editor templates

    - by artvolk
    I'm starting to use DataAnnotations in ASP.NET MVC and strongly typed template helpers. Now I have this in my views (Snippet is my custom type, Created is DateTime): <tr> <td><%= Html.LabelFor(f => Model.Snippet.Created) %>:</td> <td><%= Html.EditorFor(f => Model.Snippet.Created)%></td> </tr> The editor template for DateTime is like this: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %> <%=Html.TextBox("", Model.ToString("g"))%> But now I want to put inside editor template the whole <tr>, so I'd like to have just this in my view: <%= Html.EditorFor(f => Model.Snippet.Created)%> And something like this in editor template, but I don't know how to render for for label attribute, it should be Snippet_Created for my example, the same as id\name for textbox, so pseudo code: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %> <tr> <td><label for="<What to place here???>"><%=ViewData.ModelMetadata.DisplayName %></label></td> <td><%=Html.TextBox("", Model.ToString("g"))%></td> </tr> The Html.TextBox() have the first parameter empty and id\name for textbox is generated corectly. Thanks in advance!

    Read the article

  • How should I organize my mvc templates?

    - by CatZ
    Hi, In the new version of MVC we have been given display and editor templates. I was wondering how to make the best possible use of these. I was at first thinking in the line of creating one for a collection and one for an item in the case I want to display either as a list or single but it does not really make sense to me. I'll show you what I mean and please comment if this is wrong. I have trouble figuring it out myself. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<DisplayPhoneModel>>" %> <% foreach (var item in Model){%> <%= Html.DisplayFor(x => item) %> <%}%> So in my tiny reality that would for every item in the model search for a display template for DisplayPhoneModel. That display template could then simply look like. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DisplayPhoneModel>" %> <%= Html.LabelFor(x => x.PhoneType) %>&nbsp;<%= Html.LabelFor(x => x.PhoneNumber) %> So, question is if there is a better way to handle this? Am I at all on the right path?

    Read the article

  • Attempting to update multiple partial views from a single Ajax.ActionLink

    - by mwright
    I have a a partial view which contains other partial views. I am trying to the main partial view ( "MainPartialView" ) from an Ajax.ActionLink in a partial view contained by the main partial view ( "DetailsView" ). Everything appears to be called just fine and I can step through and it executes all of the code on the pages. However, after that is all done it throws this error in a popup box in visual studio: htmlfile: Unknown runtime error This error puts the break point in the MicrosoftAjax.js file, Line 5, Col 83,632, Ch 83632. Any thoughts? Index Page: <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script> <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script> <ul> <% foreach (DomainObject domainObject in Model) { %> <% Html.RenderPartial("MainPartialView", domainObject); %> <% } %> </ul> MainPartialView: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DomainObject>" %> <li> <div id="<%= Model.Id%>"> <%= Ajax.ActionLink("Details", "PartialViewAction", "PartialViewController", new { id = Model.Id, }, new AjaxOptions { UpdateTargetId ="UpdateTargetId" })%> <% Html.RenderPartial("Details", Model); %> <div id="Details"></div> </div> </li> Details: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DomainObject>" %> <% foreach ( var link in Model.Links) {%> <div> <div> <%= link.Name %> </div> <div> <%= Ajax.ActionLink("Submit this Action", "DoAction", "XTrademark", new { id = Model.TrademarkId, id2 = actionStateLink.ActionStateLinkId }, new AjaxOptions{ UpdateTargetId = Model.TrademarkId.ToString()} )%> </div> </div> <br /> <%} %>

    Read the article

  • Custom ViewEngine problem with ASP.NET MVC

    - by mare
    In this question jfar answered with his solution the problem is it does not work for me. In the method FindView() I have to somehow check if the View we are requesting is a ViewUserControl. Because otherwise I get an error saying: "A master name cannot be specified when the view is a ViewUserControl." This is my custom view engine code right now: public class PendingViewEngine : VirtualPathProviderViewEngine { public PendingViewEngine() { // This is where we tell MVC where to look for our files. /* {0} = view name or master page name * {1} = controller name */ MasterLocationFormats = new[] {"~/Views/Shared/{0}.master", "~/Views/{0}.master"}; ViewLocationFormats = new[] { "~/Views/{1}/{0}.aspx", "~/Views/Shared/{0}.aspx", "~/Views/Shared/{0}.ascx", "~/Views/{1}/{0}.ascx" }; PartialViewLocationFormats = new[] {"~/Views/{1}/{0}.ascx", "~/Views/Shared/{0}.ascx"}; } protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) { return new WebFormView(partialPath, ""); } protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) { return new WebFormView(viewPath, masterPath); } public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) { if (controllerContext.HttpContext.Request.IsAjaxRequest()) return base.FindView(controllerContext, viewName, "Modal", useCache); return base.FindView(controllerContext, viewName, "Site", useCache); } } The above ViewEngine fails on calls like this: <% Html.RenderAction("Display", "WidgetZoneV2", new { zoneslug = "left-default-zone" }); %> As you can see, I am providing Route values to my RenderAction call. The action I am rendering here is this: // Widget zone name is unique // GET: /WidgetZoneV2/{zoneslug} public ActionResult Display(string zoneslug) { zoneslug = Utility.RemoveIllegalCharacters(zoneslug); // Displaying widget zone creates new widget zone if it does not exist yet; so it prepares our page for // dropping of content widgets WidgetZone zone; if (!_repository.IsUniqueSlug(zoneslug)) zone = (WidgetZone) _repository.GetInstance(zoneslug); else { // replace slug with spaces to convert it into Title zone = new WidgetZone {Slug = zoneslug, Title = zoneslug.Replace('-', ' '), WidgetsList = new ContentList()}; _repository.Insert(zone); } ViewData["ContentItemsList"] = _repository.GetContentItems(); return View("WidgetZoneV2", zone); } I cannot use RenderPartial (at least I don't know how) the way I can RenderAction. To my knowledge there is no way to provide RouteValueDictionary to RenderPartial() like the way you can to RenderAction().

    Read the article

  • ASP.Net MVC, strongly typed view with DateTime not accepted?

    - by Anders Juul
    Hi all, I wish to create a view like <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %> but I get an error saying that DateTime must be a reference type in order to use for parameter TModel. Fair enough, but I google plenty of examples that implement just what I try to achieve. Any clues as to what I need to change/install/update? Any comments welcome, Anders, Denmark

    Read the article

  • asp.net mvc user control problem foreach loop

    - by mazhar
    Previous post <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" % <% MvcApplication1.Models.FeaturesRepository _model = new MvcApplication1.Models.FeaturesRepository(); % <% foreach (var md in _model.GetAllFeatures()) { % <%--<% if (md.int_ParentId == 0) { %--% <%= md.vcr_FeaturesName % <%--<% } %--% <% } % It is with reference to the previous post above.Is there something wrong with the foreach loop(The result is correct but it is displaying the series of Add,Add,Add,Add,Add,Add...,which is the last record of the getallfeatures.

    Read the article

  • ASP.NET MVC : Good Replacement for User Control?

    - by David Lively
    I found user controls to be incredibly useful when working with ASP.NET webforms. By encapsulating the code required for displaying a control with the markup, creation of reusable components was very straightforward and very, very useful. While MVC provides convenient separation of concerns, this seems to break encapsulation (ie, you can add a control without adding or using its supporting code, leading to runtime errors). Having to modify a controller every time I add a control to a view seems to me to integrate concerns, not separate them. I'd rather break the purist MVC ideology than give up the benefits of reusable, packaged controls. I need to be able to include components similar to webforms user controls throughout a site, but not for the entire site, and not at a level that belongs in a master page. These components should have their own code not just markup (to interact with the business layer), and it would be great if the page controller didn't need to know about the control. Since MVC user controls don't have codebehind, I can't see a good way to do this. Update FINALLY, a good (and, in retrospect, obvious) way to accomplish this. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace K.ObjectModel.Controls { public class TestControl : ViewUserControl { protected override void Render(System.Web.UI.HtmlTextWriter writer) { writer.Write("Hello World"); base.Render(writer); } } } Create a new class which inherits ViewUserControl Override the .Render() method as shown above. Register the control via its associated ASCX as you would in a webForm: <%@ Register TagName="tn" TagPrefix="k" Src="~/Views/Navigation/LeftBar.ascx"%> Use the corresponding tag in whatever view or master page that you need: <k:tn runat="server"/> Make sure your .ascx inherits your new control: <%@ Control Language="C#" Inherits="K.ObjectModel.Controls.TestControl" %> Voila, you're up and running. This is tested with ASP.NET MVC 2, VS 2010 and .NET 4.0. Your custom tag references the ascx partial view, which inherits from the TestControl class. The control then overrides the Render() method, which is called to render the view, giving you complete control over the process from tag to output. Why does everyone try to make this so much harder than it has to be?

    Read the article

  • ASP.Net MVC 2 Auto Complete Textbox With Custom View Model Attribute & EditorTemplate

    - by SeanMcAlinden
    In this post I’m going to show how to create a generic, ajax driven Auto Complete text box using the new MVC 2 Templates and the jQuery UI library. The template will be automatically displayed when a property is decorated with a custom attribute within the view model. The AutoComplete text box in action will look like the following:   The first thing to do is to do is visit my previous blog post to put the custom model metadata provider in place, this is necessary when using custom attributes on the view model. http://weblogs.asp.net/seanmcalinden/archive/2010/06/11/custom-asp-net-mvc-2-modelmetadataprovider-for-using-custom-view-model-attributes.aspx Once this is in place, make sure you visit the jQuery UI and download the latest stable release – in this example I’m using version 1.8.2. You can download it here. Add the jQuery scripts and css theme to your project and add references to them in your master page. Should look something like the following: Site.Master <head runat="server">     <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>     <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />     <link href="../../css/ui-lightness/jquery-ui-1.8.2.custom.css" rel="stylesheet" type="text/css" />     <script src="../../Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>     <script src="../../Scripts/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script> </head> Once this is place we can get started. Creating the AutoComplete Custom Attribute The auto complete attribute will derive from the abstract MetadataAttribute created in my previous post. It will look like the following: AutoCompleteAttribute using System.Collections.Generic; using System.Web.Mvc; using System.Web.Routing; namespace Mvc2Templates.Attributes {     public class AutoCompleteAttribute : MetadataAttribute     {         public RouteValueDictionary RouteValueDictionary;         public AutoCompleteAttribute(string controller, string action, string parameterName)         {             this.RouteValueDictionary = new RouteValueDictionary();             this.RouteValueDictionary.Add("Controller", controller);             this.RouteValueDictionary.Add("Action", action);             this.RouteValueDictionary.Add(parameterName, string.Empty);         }         public override void Process(ModelMetadata modelMetaData)         {             modelMetaData.AdditionalValues.Add("AutoCompleteUrlData", this.RouteValueDictionary);             modelMetaData.TemplateHint = "AutoComplete";         }     } } As you can see, the constructor takes in strings for the controller, action and parameter name. The parameter name will be used for passing the search text within the auto complete text box. The constructor then creates a new RouteValueDictionary which we will use later to construct the url for getting the auto complete results via ajax. The main interesting method is the method override called Process. With the process method, the route value dictionary is added to the modelMetaData AdditionalValues collection. The TemplateHint is also set to AutoComplete, this means that when the view model is parsed for display, the MVC 2 framework will look for a view user control template called AutoComplete, if it finds one, it uses that template to display the property. The View Model To show you how the attribute will look, this is the view model I have used in my example which can be downloaded at the end of this post. View Model using System.ComponentModel; using Mvc2Templates.Attributes; namespace Mvc2Templates.Models {     public class TemplateDemoViewModel     {         [AutoComplete("Home", "AutoCompleteResult", "searchText")]         [DisplayName("European Country Search")]         public string SearchText { get; set; }     } } As you can see, the auto complete attribute is called with the controller name, action name and the name of the action parameter that the search text will be passed into. The AutoComplete Template Now all of this is in place, it’s time to create the AutoComplete template. Create a ViewUserControl called AutoComplete.ascx at the following location within your application – Views/Shared/EditorTemplates/AutoComplete.ascx Add the following code: AutoComplete.ascx <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <%     var propertyName = ViewData.ModelMetadata.PropertyName;     var propertyValue = ViewData.ModelMetadata.Model;     var id = Guid.NewGuid().ToString();     RouteValueDictionary urlData =         (RouteValueDictionary)ViewData.ModelMetadata.AdditionalValues.Where(x => x.Key == "AutoCompleteUrlData").Single().Value;     var url = Mvc2Templates.Views.Shared.Helpers.RouteHelper.GetUrl(this.ViewContext.RequestContext, urlData); %> <input type="text" name="<%= propertyName %>" value="<%= propertyValue %>" id="<%= id %>" class="autoComplete" /> <script type="text/javascript">     $(function () {         $("#<%= id %>").autocomplete({             source: function (request, response) {                 $.ajax({                     url: "<%= url %>" + request.term,                     dataType: "json",                     success: function (data) {                         response(data);                     }                 });             },             minLength: 2         });     }); </script> There is a lot going on in here but when you break it down it’s quite simple. Firstly, the property name and property value are retrieved through the model meta data. These are required to ensure that the text box input has the correct name and data to allow for model binding. If you look at line 14 you can see them being used in the text box input creation. The interesting bit is on line 8 and 9, this is the code to retrieve the route value dictionary we added into the model metada via the custom attribute. Line 11 is used to create the url, in order to do this I created a quick helper class which looks like the code below titled RouteHelper. The last bit of script is the code to initialise the jQuery UI AutoComplete control with the correct url for calling back to our controller action. RouteHelper using System.Web.Mvc; using System.Web.Routing; namespace Mvc2Templates.Views.Shared.Helpers {     public static class RouteHelper     {         const string Controller = "Controller";         const string Action = "Action";         const string ReplaceFormatString = "REPLACE{0}";         public static string GetUrl(RequestContext requestContext, RouteValueDictionary routeValueDictionary)         {             RouteValueDictionary urlData = new RouteValueDictionary();             UrlHelper urlHelper = new UrlHelper(requestContext);                          int i = 0;             foreach(var item in routeValueDictionary)             {                 if (item.Value == string.Empty)                 {                     i++;                     urlData.Add(item.Key, string.Format(ReplaceFormatString, i.ToString()));                 }                 else                 {                     urlData.Add(item.Key, item.Value);                 }             }             var url = urlHelper.RouteUrl(urlData);             for (int index = 1; index <= i; index++)             {                 url = url.Replace(string.Format(ReplaceFormatString, index.ToString()), string.Empty);             }             return url;         }     } } See it in action All you need to do to see it in action is pass a view model from your controller with the new AutoComplete attribute attached and call the following within your view: <%= this.Html.EditorForModel() %> NOTE: The jQuery UI auto complete control expects a JSON string returned from your controller action method… as you can’t use the JsonResult to perform GET requests, use a normal action result, convert your data into json and return it as a string via a ContentResult. If you download the solution it will be very clear how to handle the controller and action for this demo. The full source code for this post can be downloaded here. It has been developed using MVC 2 and Visual Studio 2010. As always, I hope this has been interesting/useful. Kind Regards, Sean McAlinden.

    Read the article

  • Unobtrusive Client Side Validation with Dynamic Contents in ASP.NET MVC 3

    - by imran_ku07
        Introduction:          A while ago, I blogged about how to perform client side validation for dynamic contents in ASP.NET MVC 2 at here. Using the approach given in that blog, you can easily validate your dynamic ajax contents at client side. ASP.NET MVC 3 also supports unobtrusive client side validation in addition to ASP.NET MVC 2 client side validation for backward compatibility. I feel it is worth to rewrite that blog post for ASP.NET MVC 3 unobtrusive client side validation. In this article I will show you how to do this.       Description:           I am going to use the same example presented at here. Create a new ASP.NET MVC 3 application. Then just open HomeController.cs and add the following code,   public ActionResult CreateUser() { return View(); } [HttpPost] public ActionResult CreateUserPrevious(UserInformation u) { return View("CreateUserInformation", u); } [HttpPost] public ActionResult CreateUserInformation(UserInformation u) { if(ModelState.IsValid) return View("CreateUserCompanyInformation"); return View("CreateUserInformation"); } [HttpPost] public ActionResult CreateUserCompanyInformation(UserCompanyInformation uc, UserInformation ui) { if (ModelState.IsValid) return Content("Thank you for submitting your information"); return View("CreateUserCompanyInformation"); }             Next create a CreateUser view and add the following lines,   <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<UnobtrusiveValidationWithDynamicContents.Models.UserInformation>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> CreateUser </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <div id="dynamicData"> <%Html.RenderPartial("CreateUserInformation"); %> </div> </asp:Content>             Next create a CreateUserInformation partial view and add the following lines,   <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<UnobtrusiveValidationWithDynamicContents.Models.UserInformation>" %> <% Html.EnableClientValidation(); %> <%using (Html.BeginForm("CreateUserInformation", "Home")) { %> <table id="table1"> <tr style="background-color:#E8EEF4;font-weight:bold"> <td colspan="3" align="center"> User Information </td> </tr> <tr> <td> First Name </td> <td> <%=Html.TextBoxFor(a => a.FirstName)%> </td> <td> <%=Html.ValidationMessageFor(a => a.FirstName)%> </td> </tr> <tr> <td> Last Name </td> <td> <%=Html.TextBoxFor(a => a.LastName)%> </td> <td> <%=Html.ValidationMessageFor(a => a.LastName)%> </td> </tr> <tr> <td> Email </td> <td> <%=Html.TextBoxFor(a => a.Email)%> </td> <td> <%=Html.ValidationMessageFor(a => a.Email)%> </td> </tr> <tr> <td colspan="3" align="center"> <input type="submit" name="userInformation" value="Next"/> </td> </tr> </table> <%} %> <script type="text/javascript"> $("form").submit(function (e) { if ($(this).valid()) { $.post('<%= Url.Action("CreateUserInformation")%>', $(this).serialize(), function (data) { $("#dynamicData").html(data); $.validator.unobtrusive.parse($("#dynamicData")); }); } e.preventDefault(); }); </script>             Next create a CreateUserCompanyInformation partial view and add the following lines,   <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<UnobtrusiveValidationWithDynamicContents.Models.UserCompanyInformation>" %> <% Html.EnableClientValidation(); %> <%using (Html.BeginForm("CreateUserCompanyInformation", "Home")) { %> <table id="table1"> <tr style="background-color:#E8EEF4;font-weight:bold"> <td colspan="3" align="center"> User Company Information </td> </tr> <tr> <td> Company Name </td> <td> <%=Html.TextBoxFor(a => a.CompanyName)%> </td> <td> <%=Html.ValidationMessageFor(a => a.CompanyName)%> </td> </tr> <tr> <td> Company Address </td> <td> <%=Html.TextBoxFor(a => a.CompanyAddress)%> </td> <td> <%=Html.ValidationMessageFor(a => a.CompanyAddress)%> </td> </tr> <tr> <td> Designation </td> <td> <%=Html.TextBoxFor(a => a.Designation)%> </td> <td> <%=Html.ValidationMessageFor(a => a.Designation)%> </td> </tr> <tr> <td colspan="3" align="center"> <input type="button" id="prevButton" value="Previous"/>   <input type="submit" name="userCompanyInformation" value="Next"/> <%=Html.Hidden("FirstName")%> <%=Html.Hidden("LastName")%> <%=Html.Hidden("Email")%> </td> </tr> </table> <%} %> <script type="text/javascript"> $("#prevButton").click(function () { $.post('<%= Url.Action("CreateUserPrevious")%>', $($("form")[0]).serialize(), function (data) { $("#dynamicData").html(data); $.validator.unobtrusive.parse($("#dynamicData")); }); }); $("form").submit(function (e) { if ($(this).valid()) { $.post('<%= Url.Action("CreateUserCompanyInformation")%>', $(this).serialize(), function (data) { $("#dynamicData").html(data); $.validator.unobtrusive.parse($("#dynamicData")); }); } e.preventDefault(); }); </script>             Next create a new class file UserInformation.cs inside Model folder and add the following code,   public class UserInformation { public int Id { get; set; } [Required(ErrorMessage = "First Name is required")] [StringLength(10, ErrorMessage = "First Name max length is 10")] public string FirstName { get; set; } [Required(ErrorMessage = "Last Name is required")] [StringLength(10, ErrorMessage = "Last Name max length is 10")] public string LastName { get; set; } [Required(ErrorMessage = "Email is required")] [RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email Format is wrong")] public string Email { get; set; } }             Next create a new class file UserCompanyInformation.cs inside Model folder and add the following code,    public class UserCompanyInformation { public int UserId { get; set; } [Required(ErrorMessage = "Company Name is required")] [StringLength(10, ErrorMessage = "Company Name max length is 10")] public string CompanyName { get; set; } [Required(ErrorMessage = "CompanyAddress is required")] [StringLength(50, ErrorMessage = "Company Address max length is 50")] public string CompanyAddress { get; set; } [Required(ErrorMessage = "Designation is required")] [StringLength(50, ErrorMessage = "Designation max length is 10")] public string Designation { get; set; } }            Next add the necessary script files in Site.Master,   <script src="<%= Url.Content("~/Scripts/jquery-1.4.4.min.js")%>" type="text/javascript"></script> <script src="<%= Url.Content("~/Scripts/jquery.validate.min.js")%>" type="text/javascript"></script> <script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%>" type="text/javascript"></script>            Now run this application. You will get the same behavior as described in this article. The key important feature to note here is the $.validator.unobtrusive.parse method, which is used by ASP.NET MVC 3 unobtrusive client side validation to initialize jQuery validation plug-in to start the client side validation process. Another important method to note here is the jQuery.valid method which return true if the form is valid and return false if the form is not valid .       Summary:          There may be several occasions when you need to load your HTML contents dynamically. These dynamic HTML contents may also include some input elements and you need to perform some client side validation for these input elements before posting thier values to server. In this article I shows you how you can enable client side validation for dynamic input elements in ASP.NET MVC 3. I am also attaching a sample application. Hopefully you will enjoy this article too.   SyntaxHighlighter.all()

    Read the article

  • JavaScript and CSS files for ASP.NET MVC 2 EditorTemplate user controls

    - by Zack Peterson
    I'm using an EditorTemplate DateTime.ascx in my ASP.NET MVC 2 project. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime>" %> <%: Html.TextBox(String.Empty, Model.ToString("M/dd/yyyy h:mm tt")) %> <script type="text/javascript"> $(function () { $('#<%: ViewData.TemplateInfo.GetFullHtmlFieldId(String.Empty) %>').AnyTime_picker({ format: "%c/%d/%Y %l:%i %p" }); }); </script> This uses the Any+Time™ JavaScript library for jQuery by Andrew M. Andrews III. I've added those library files (anytimec.js and anytimec.css) to the <head> section of my master page. Rather than include these JavaScript and Cascading Style Sheet files on every page of my web site, how can I instead include the .js and .css files only on pages that need them--pages that edit a DateTime type value?

    Read the article

  • ASP.NET MVC stack overflow exception when calling a partial view from master page

    - by quakkels
    Hey there everyone, I'm getting a stack overflow error when I try to call a partial view from the master. The Partial View: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <form action="/members/TestLoginProcess/" method="post"> U: <input type="text" name="mUsername" /><br /> P: <input type="password" name="mHash" /><br /> <button type="submit">Log In</button> </form> The Action in the "Members" controller [ChildActionOnly] public ActionResult TestLogin() { return PartialView(); } Then I call the partial view from the master page: <!--Excerpt from wopr.master--> <%= Html.Action("TestLogin", "Members")%> When I go into debug mode the master page returns this error: {Cannot evaluate expression because the current thread is in a stack overflow state.} I don't understand how this error is getting triggered. any help would be much appreciated!

    Read the article

  • Edit and Create view using EditCreate.ascx partial in ASP.NET MVC

    - by mare
    If you look at the NerdDinner example of creating and editing dinners then you see they use a partial (ViewUserControl or ASCX) DinnerForm to put the functionality of creating and editing dinners into one file because it is essential the same and they use it using RenderPartial("DinnerForm"). This approach seems fine for me but I've run into a problem where you have to add additonal route values or html properties to the Form tag. This picks up the current action and controller automatically: <% using (Html.BeginForm()) { %> However, if I use another BeginForm() overload which allows to pass in enctype or any other attribute I have to do it like this: <% using ("Create", "Section", new { modal = true }, FormMethod.Post, new { enctype = "multipart/form-data" })) and as you can see we lose the ability to automatically detect in which View we are calling RenderPartial("OurCreateEditFormPartial"). We can't have hardcoded values in there because in Edit View this postback will fail or won't postback to the right controller action. What should I do in this case?

    Read the article

1 2 3 4 5  | Next Page >