Search Results

Search found 18 results on 1 pages for 'editortemplates'.

Page 1/1 | 1 

  • custom MVC2 editortemplates

    - by tschreck
    i would like to create a library of custom EditorTemplates and DisplayTemplates. How do I "load" these into my MVC application? I want to be able to re-use my custom template library across a variety of MVC apps.

    Read the article

  • ASP.Net MVC 2 DropDownListFor in EditorTemplate

    - by tschreck
    I have a view model that looks like this: namespace AutoForm.Models { public class ProductViewModel { [UIHint("DropDownList")] public String Category { get; set; } [ScaffoldColumn(false)] public IEnumerable<SelectListItem> CategoryList { get; set; } ... } } It has Category and CategoryList properties. The CategoryList is the source data for the Category dropdown UI element. I have an EditorTemplate that looks like this: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ProductViewModel>" %> <%@ Import Namespace="AutoForm.Models"%> <%=Html.DropDownListFor(m => m.Category , Model.CategoryList ) %> NOTE: this EditorTemplate is strongly typed to ProductViewModel My Controller is populating CategoryList property with data from a database. I cannot get the DropDownListFor template to render a drop down list with data from CategoryList. I know CategoryList is getting populated with data in the controller because I see the data when I debug and step through the controller. Here's my error message in the browser: Server Error in '/' Application. Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error: Line 2: <%@ Import Namespace="AutoForm.Models"% Line 3: Line 4: <%=Html.DropDownListFor(m = m.Category, Model.CategoryList) % Source File: c:\ProjectStore\AutoForm\AutoForm\Views\Shared\EditorTemplates\DropDownList.ascx Line: 4 Any ideas? Thanks Tom As a followup, I noticed that ViewData.Model is null when I'm stepping through the code in the EditorTemplate. I have the EditorTemplate strongly typed to "ProductViewModel" which is also the type that's passed to the View in the controller. I'm perplexed as to why ViewData.Model is null even though it's getting populated in the controller before getting passed to the view.

    Read the article

  • Asp.Net MVC EditorTemplate Model is lost after Post

    - by Farrell
    I have a controller with two simple Methods: UserController Methods: [AcceptVerbs(HttpVerbs.Get)] public ActionResult Details(string id) { User user = UserRepo.UserByID(id); return View(user); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Details(User user) { return View(user); } Then there is one simple view for displaying the details: <% using (Html.BeginForm("Details", "User", FormMethod.Post)) {%> <fieldset> <legend>Userinfo</legend> <%= Html.EditorFor(m => m.Name, "LabelTextBoxValidation")%> <%= Html.EditorFor(m => m.Email, "LabelTextBoxValidation")%> <%= Html.EditorFor(m => m.Telephone, "LabelTextBoxValidation")%> </fieldset> <input type="submit" id="btnChange" value="Change" /> <% } %> As you can see, I use an editor template "LabelTextBoxValidation": <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %> <%= Html.Label("") %> <%= Html.TextBox(Model,Model)%> <%= Html.ValidationMessage("")%> Showing user information is no problem. The view renders perfectly user details. When I submit the form, the object user is lost. I debugged on the row "return View(User);" in the Post Details method, the user object is filled with nullable values. If I dont use the editor template, the user object is filled with correct data. So there has to be something wrong with the editor template, but can't figure out what it is. Suggestions?

    Read the article

  • How can I validate the result in an ASP.NET MVC editor template?

    - by Morten Christiansen
    I have created an editor template for representing selecting from a dynamic dropdown list and it works as it should except for validation, which I have been unable to figure out. If the model has the [Required] attribute set, I want that to invalidate if the default option is selected. The view model object that must be represented as the dropdown list is Selector: public class Selector { public int SelectedId { get; set; } public IEnumerable<Pair<int, string>> Choices { get; private set; } public string DefaultValue { get; set; } public Selector() { //For binding the object on Post } public Selector(IEnumerable<Pair<int, string>> choices, string defaultValue) { DefaultValue = defaultValue; Choices = choices; } } The editor template looks like this: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <select class="template-selector" id="<%= ViewData.ModelMetadata.PropertyName %>.SelectedId" name="<%= ViewData.ModelMetadata.PropertyName %>.SelectedId"> <% var model = ViewData.ModelMetadata.Model as QASW.Web.Mvc.Selector; if (model != null) { %> <option><%= model.DefaultValue %></option><% foreach (var choice in model.Choices) { %> <option value="<%= choice.Value1 %>"><%= choice.Value2 %></option><% } } %> </select> I sort of got it to work by calling it from the view like this (where Category is a Selector): <%= Html.ValidationMessageFor(n => n.Category.SelectedId)%> But it shows the validation error for not supplying a proper number and it does not care if I set the Required attribute.

    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

  • ForEach with EditorFor

    - by hermiod
    I have got an Entity model which contains a collection of Message objects which are of the type Message which has several properties, including content, MessageID, from, and to. I have created an EditorTemplate for type Message, however, I cannot get it to display the contents of the Messages collection. There are no errors, but nothing is output. Please note that the view code is from an EditorTemplate for the parent Talkback class. Can you have an EditorTemplate calling another EditorTemplate for a child collection? Both the Talkback and Message class are generated by Entity framework from an existing database. View code: <% foreach (TalkbackEntityTest.Message msg in Model.Messages) { Html.EditorFor(x=> msg, "Message"); } %> This is my template code. It is the standard auto-generated view code with some minor changes. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<TalkbackEntityTest.Message>" %> <%: Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div class="editor-label"> <%: Html.LabelFor(model => model.MessageID) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.MessageID) %> <%: Html.ValidationMessageFor(model => model.MessageID) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.acad_period) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.acad_period) %> <%: Html.ValidationMessageFor(model => model.acad_period) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.talkback_id) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.talkback_id) %> <%: Html.ValidationMessageFor(model => model.talkback_id) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.From) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.From) %> <%: Html.ValidationMessageFor(model => model.From) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.To) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.To) %> <%: Html.ValidationMessageFor(model => model.To) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.SentDatetime) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.SentDatetime, String.Format("{0:g}", Model.SentDatetime)) %> <%: Html.ValidationMessageFor(model => model.SentDatetime) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.content) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.content) %> <%: Html.ValidationMessageFor(model => model.content) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.MessageTypeID) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.MessageTypeID) %> <%: Html.ValidationMessageFor(model => model.MessageTypeID) %> </div> <p> <input type="submit" value="Save" /> </p> </fieldset> There is definitely content in the Message collection as, if I remove EditorFor and put in response.write on the content property of the Message class, I get the content field for 3 Message objects on the page, which is exactly as expected.

    Read the article

  • Limit JavaScript and CSS files on ASP.NET MVC 2 Master Page based on Model and View content

    - by Zack Peterson
    I want to include certain .js and .css files only on pages that need them. For example, my EditorTemplate DateTime.ascx needs files anytimec.js and anytimec.css. That template is applied whenever I use either the EditorFor or EditorForModel helper methods in a view for a model with a DateTime type value. I've put this condition into the <head> section of my master page. It checks for a DateTime type property in the ModelMetadata. <% if (this.ViewData.ModelMetadata.Properties.Any(p => p.ModelType == typeof(DateTime))) { %> <link href="../../Content/anytimec.css" rel="stylesheet" type="text/css" /> <script src="../../Scripts/anytimec.js" type="text/javascript"></script> <% } %> This has two problems: Fails if I have nested child models of type DateTime Unnecessarily triggered by views without EditorFor or EditorForModel methods (example: DisplayForModel) How can I improve this technique?

    Read the article

  • Too many JavaScript and CSS files on my ASP.NET MVC 2 Master Page?

    - 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

  • WPF more dynamic views and DataAnnotations

    - by Ingó Vals
    Comparing WPF and Asp.Net Razor/HtmlHelper I find WPF/Xaml to be somewhat lacking in creating views. With HtmlHelpers you could define in one place how you wan't to represent specific type of data and include elements set from the DataAnnotations of the property. In WPF you can also define DataTemplates for data but it seems much more limited then EditorTemplates. It doesn't use information from DataAnnotations. Also the layout of elements can be bothersome. I hate having to constantly add RowDefinitions and update the Grid.Row attribute of lot of elements when I add a new property somewhere in line. I understand that GUI programming can be a lot of grunt work like this but as Asp.Net MVC has shown there are ways around that. What solutions are out there to make view creation in WPF a little bit cleaner, maintainable and more dynamic?

    Read the article

  • Html.EditorFor, Html.DisplayFor not working on MVC1.0 -> MVC2.0 manual migration

    - by lawrence-chase
    Has anyone encountered this problem? I manually migrated a MVC1.0 application to MVC2.0 and everything so far seems to be working fine. Today I wanted to try out the Html.EditorFor helper and it doesn't render the template. I set it up the same way in a fresh MVC2.0 application and the template does render. Is there anything other (or specifically needed when mirgrating to activate this behavior) than throwing the partial view like DateTime.ascx into Views/Shared/EditorTemplates and using the helper methods to render the model objects? I'm stumped.

    Read the article

  • asp.net MVC DisplayTemplates and EditorTemplate naming convention

    - by Simon G
    Hi, I've got a couple of questions about the naming convention for the DisplayTemplates and EditorTemplates in MVC 2. If for example I have a customer object with a child list of account how do I: Create a display template for the list of accounts, what is the file called? When I'm doing a foreach( var c in Model.Accounts ) how do I call a display temple while in the foreach loop? When I do Html.DisplayFor( x => x ) inside the foreach x is the model and not in this case c. Thanks in advance.

    Read the article

  • ASP.NET MVC2 Radio Button generates duplicate HTML id-s

    - by Dmitriy Nagirnyak
    Hi, It seems that the default ASP.NET MVC2 Html helper generates duplicate HTML IDs when using code like this (EditorTemplates/UserType.ascx): <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<UserType>" %> <%: Html.RadioButton("", UserType.Primary, Model == UserType.Primary) %> <%: Html.RadioButton("", UserType.Standard, Model == UserType.Standard) %> <%: Html.RadioButton("", UserType.ReadOnly, Model == UserType.ReadOnly) %> The HTML it produces is: <input checked="checked" id="UserType" name="UserType" type="radio" value="Primary" /> <input id="UserType" name="UserType" type="radio" value="Standard" /> <input id="UserType" name="UserType" type="radio" value="ReadOnly" /> That clearly shows a problem. So I must be misusing the Helper or something. I can manually specify the id as html attribute but then I cannot guarantee it will be unique. So the question is how to make sure that the IDs generated by RadioButton helper are unique for each value and still preserve the conventions for generating those IDs (so nested models are respected? (Preferably not generating IDs manually.) Thanks, Dmitriy,

    Read the article

  • .net MVC RenderPartial renders information that is not in the model

    - by Andreas
    Hi, I have a usercontrol that is rendering a list of items. Each row contains a unique id in a hidden field, a text and a delete button. When clicking on the delete button I use jquery ajax to call the controller method DeleteCA (seen below). DeleteCA returns a new list of items that replaces the old list. [HttpPost] public PartialViewResult DeleteCA(CAsViewModel CAs, Guid CAIdToDelete) { int indexToRemove = CAs.CAList.IndexOf(CAs.CAList.Single(m => m.Id == CAIdToDelete)); CAs.CAList.RemoveAt(indexToRemove); return PartialView("EditorTemplates/CAs", CAs); } I have checked that DeleteCA is really removing the correct item. The modified list of CAs passed to PartialView no longer contains the deleted item. Something weird happens when the partial view is rendered. The number of items in the list is reduced but it is always the last element that is removed from the list. The rendered items does not correspond to the items in the list/model sent to PartialView. In the usercontrol file (ascx) I'm using both Model.CAList and lambda expression m = m.CAList. How is it possible for the usercontrol to render stuff that is not in the model sent to PartialView? Thanx Andreas

    Read the article

  • Using of Templated Helpers in MVC 2.0 : How can use the name of the property that I'm rendering insi

    - by Andrey Tagaew
    Hi. I'm reviewing new features of ASP.NET MVC 2.0. During the review i found really interesting using Templated Helpers. As they described it, the primary reason of using them is to provide common way of how some datatypes should be rendered. Now i want to use this way in my project for DateTime datatype My project was written for the MVC 1.0 so generating of editbox is looking like this: <%= Html.TextBox("BirthDate", Model.BirthDate, new { maxlength = 10, size = 10, @class = "BirthDate-date" })%> <script type="text/javascript"> $(document).ready(function() { $(".BirthDate-date").datepicker({ showOn: 'button', buttonImage: '<%=Url.Content("~/images/i_calendar.gif") %>', buttonImageOnly: true }); }); </script> Now i want to use Template Helper, so i want to have above code once i type next sentence: <%=Html.EditorFor(f=>f.BirthDate) %> According to the manual I create DataTime.ascx partial view inside Shared/EditorTemplates folder. I put there above code and stacked with the problem. How can i pass the name of the property that I'm rendering with template helper? As you can see from my example, i really need it, since I'm using the name of the property to specify data value and parameter name that will be send during the POST requsest. Also, I'm using it to generate class name for JS calendar building. I tried to remove my partial class for template helper and made MVC to generate its default behavior. Here what it generated for me: <input type="text" value="04/29/2010" name="LoanApplicationDays" id="LoanApplicationDays" class="text-box single-line"> As you can see, it used the name of the property for "name" and "id" attributes. This example let me to presume that Template Helper knows about the name of the property. So, there should be some way of how to use it in custom implementation. Thanks for your help!

    Read the article

  • jPlayer widget created with static error as result

    - by goldengel
    I've created a widged with Orchard. Unfortunately I've used the same "Title" for a jPlayer widget twice. Now I receive an error: Server Error in '/wgk' Application. Sequence contains more than one element Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: Sequence contains more than one element Source Error: Line 2: <fieldset> Line 3: <div>@Html.LabelFor(o => o.MediaGalleryName, @T("Media gallery"))</div> Line 4: @if(!Model.HasAvailableGalleries) { Line 5: <div>@T("You need first to create an media gallery on Media Gallery menu")</div> Line 6: } Source File: x:\Intepub\wgk\Modules\Orchard.jPlayer\Views\EditorTemplates\Parts\MediaGallery.cshtml Line: 4 Stack Trace: [InvalidOperationException: Sequence contains more than one element] System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +4206966 NHibernate.Linq.Visitors.ImmediateResultsVisitor`1.HandleSingleOrDefaultCall(MethodCallExpression call) +51 NHibernate.Linq.Visitors.ImmediateResultsVisitor`1.VisitMethodCall(MethodCallExpression call) +411 NHibernate.Linq.Visitors.ExpressionVisitor.Visit(Expression exp) +371 In MediaGallery.cshtml (found in error description above) is written: @model Orchard.jPlayer.Models.MediaGalleryPart <fieldset> <div>@Html.LabelFor(o => o.MediaGalleryName, @T("Media gallery"))</div> @if(!Model.HasAvailableGalleries) { <div>@T("You need first to create an media gallery on Media Gallery menu")</div> } else { <div>@Html.DropDownListFor(o => o.SelectedGallery, Model.AvailableGalleries)</div> <div>@Html.LabelFor(o => o.SelectedType, @T("Media gallery type"))</div> <div>@Html.DropDownListFor(o => o.SelectedType, Model.AvailableTypes)</div> <div>@Html.LabelFor(o => o.AutoPlay, @T("Auto play"))</div> <div>@Html.CheckBoxFor(o => o.AutoPlay)</div> } </fieldset> My problem is now, I cannot find or edit the widget with double used name. I would love to replace it to another name. But I do not know where to do this. Please advice.

    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

  • Adding Client Validation To DataAnnotations DataType Attribute

    - by srkirkland
    The System.ComponentModel.DataAnnotations namespace contains a validation attribute called DataTypeAttribute, which takes an enum specifying what data type the given property conforms to.  Here are a few quick examples: public class DataTypeEntity { [DataType(DataType.Date)] public DateTime DateTime { get; set; }   [DataType(DataType.EmailAddress)] public string EmailAddress { get; set; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } This attribute comes in handy when using ASP.NET MVC, because the type you specify will determine what “template” MVC uses.  Thus, for the DateTime property if you create a partial in Views/[loc]/EditorTemplates/Date.ascx (or cshtml for razor), that view will be used to render the property when using any of the Html.EditorFor() methods. One thing that the DataType() validation attribute does not do is any actual validation.  To see this, let’s take a look at the EmailAddress property above.  It turns out that regardless of the value you provide, the entity will be considered valid: //valid new DataTypeEntity {EmailAddress = "Foo"}; .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Hmmm.  Since DataType() doesn’t validate, that leaves us with two options: (1) Create our own attributes for each datatype to validate, like [Date], or (2) add validation into the DataType attribute directly.  In this post, I will show you how to hookup client-side validation to the existing DataType() attribute for a desired type.  From there adding server-side validation would be a breeze and even writing a custom validation attribute would be simple (more on that in future posts). Validation All The Way Down Our goal will be to leave our DataTypeEntity class (from above) untouched, requiring no reference to System.Web.Mvc.  Then we will make an ASP.NET MVC project that allows us to create a new DataTypeEntity and hookup automatic client-side date validation using the suggested “out-of-the-box” jquery.validate bits that are included with ASP.NET MVC 3.  For simplicity I’m going to focus on the only DateTime field, but the concept is generally the same for any other DataType. Building a DataTypeAttribute Adapter To start we will need to build a new validation adapter that we can register using ASP.NET MVC’s DataAnnotationsModelValidatorProvider.RegisterAdapter() method.  This method takes two Type parameters; The first is the attribute we are looking to validate with and the second is an adapter that should subclass System.Web.Mvc.ModelValidator. Since we are extending DataAnnotations we can use the subclass of ModelValidator called DataAnnotationsModelValidator<>.  This takes a generic argument of type DataAnnotations.ValidationAttribute, which lucky for us means the DataTypeAttribute will fit in nicely. So starting from there and implementing the required constructor, we get: public class DataTypeAttributeAdapter : DataAnnotationsModelValidator<DataTypeAttribute> { public DataTypeAttributeAdapter(ModelMetadata metadata, ControllerContext context, DataTypeAttribute attribute) : base(metadata, context, attribute) { } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Now you have a full-fledged validation adapter, although it doesn’t do anything yet.  There are two methods you can override to add functionality, IEnumerable<ModelValidationResult> Validate(object container) and IEnumerable<ModelClientValidationRule> GetClientValidationRules().  Adding logic to the server-side Validate() method is pretty straightforward, and for this post I’m going to focus on GetClientValidationRules(). Adding a Client Validation Rule Adding client validation is now incredibly easy because jquery.validate is very powerful and already comes with a ton of validators (including date and regular expressions for our email example).  Teamed with the new unobtrusive validation javascript support we can make short work of our ModelClientValidationDateRule: public class ModelClientValidationDateRule : ModelClientValidationRule { public ModelClientValidationDateRule(string errorMessage) { ErrorMessage = errorMessage; ValidationType = "date"; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } If your validation has additional parameters you can the ValidationParameters IDictionary<string,object> to include them.  There is a little bit of conventions magic going on here, but the distilled version is that we are defining a “date” validation type, which will be included as html5 data-* attributes (specifically data-val-date).  Then jquery.validate.unobtrusive takes this attribute and basically passes it along to jquery.validate, which knows how to handle date validation. Finishing our DataTypeAttribute Adapter Now that we have a model client validation rule, we can return it in the GetClientValidationRules() method of our DataTypeAttributeAdapter created above.  Basically I want to say if DataType.Date was provided, then return the date rule with a given error message (using ValidationAttribute.FormatErrorMessage()).  The entire adapter is below: public class DataTypeAttributeAdapter : DataAnnotationsModelValidator<DataTypeAttribute> { public DataTypeAttributeAdapter(ModelMetadata metadata, ControllerContext context, DataTypeAttribute attribute) : base(metadata, context, attribute) { }   public override System.Collections.Generic.IEnumerable<ModelClientValidationRule> GetClientValidationRules() { if (Attribute.DataType == DataType.Date) { return new[] { new ModelClientValidationDateRule(Attribute.FormatErrorMessage(Metadata.GetDisplayName())) }; }   return base.GetClientValidationRules(); } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Putting it all together Now that we have an adapter for the DataTypeAttribute, we just need to tell ASP.NET MVC to use it.  The easiest way to do this is to use the built in DataAnnotationsModelValidatorProvider by calling RegisterAdapter() in your global.asax startup method. DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DataTypeAttribute), typeof(DataTypeAttributeAdapter)); .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Show and Tell Let’s see this in action using a clean ASP.NET MVC 3 project.  First make sure to reference the jquery, jquery.vaidate and jquery.validate.unobtrusive scripts that you will need for client validation. Next, let’s make a model class (note we are using the same built-in DataType() attribute that comes with System.ComponentModel.DataAnnotations). public class DataTypeEntity { [DataType(DataType.Date, ErrorMessage = "Please enter a valid date (ex: 2/14/2011)")] public DateTime DateTime { get; set; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Then we make a create page with a strongly-typed DataTypeEntity model, the form section is shown below (notice we are just using EditorForModel): @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>Fields</legend>   @Html.EditorForModel()   <p> <input type="submit" value="Create" /> </p> </fieldset> } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } The final step is to register the adapter in our global.asax file: DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DataTypeAttribute), typeof(DataTypeAttributeAdapter)); Now we are ready to run the page: Looking at the datetime field’s html, we see that our adapter added some data-* validation attributes: <input type="text" value="1/1/0001" name="DateTime" id="DateTime" data-val-required="The DateTime field is required." data-val-date="Please enter a valid date (ex: 2/14/2011)" data-val="true" class="text-box single-line valid"> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Here data-val-required was added automatically because DateTime is non-nullable, and data-val-date was added by our validation adapter.  Now if we try to add an invalid date: Our custom error message is displayed via client-side validation as soon as we tab out of the box.  If we didn’t include a custom validation message, the default DataTypeAttribute “The field {0} is invalid” would have been shown (of course we can change the default as well).  Note we did not specify server-side validation, but in this case we don’t have to because an invalid date will cause a server-side error during model binding. Conclusion I really like how easy it is to register new data annotations model validators, whether they are your own or, as in this post, supplements to existing validation attributes.  I’m still debating about whether adding the validation directly in the DataType attribute is the correct place to put it versus creating a dedicated “Date” validation attribute, but it’s nice to know either option is available and, as we’ve seen, simple to implement. I’m also working through the nascent stages of an open source project that will create validation attribute extensions to the existing data annotations providers using similar techniques as seen above (examples: Email, Url, EqualTo, Min, Max, CreditCard, etc).  Keep an eye on this blog and subscribe to my twitter feed (@srkirkland) if you are interested for announcements.

    Read the article

  • Yet Another ASP.NET MVC CRUD Tutorial

    - by Ricardo Peres
    I know that I have not posted much on MVC, mostly because I don’t use it on my daily life, but since I find it so interesting, and since it is gaining such popularity, I will be talking about it much more. This time, it’s about the most basic of scenarios: CRUD. Although there are several ASP.NET MVC tutorials out there that cover ordinary CRUD operations, I couldn’t find any that would explain how we can have also AJAX, optimistic concurrency control and validation, using Entity Framework Code First, so I set out to write one! I won’t go into explaining what is MVC, Code First or optimistic concurrency control, or AJAX, I assume you are all familiar with these concepts by now. Let’s consider an hypothetical use case, products. For simplicity, we only want to be able to either view a single product or edit this product. First, we need our model: 1: public class Product 2: { 3: public Product() 4: { 5: this.Details = new HashSet<OrderDetail>(); 6: } 7:  8: [Required] 9: [StringLength(50)] 10: public String Name 11: { 12: get; 13: set; 14: } 15:  16: [Key] 17: [ScaffoldColumn(false)] 18: [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 19: public Int32 ProductId 20: { 21: get; 22: set; 23: } 24:  25: [Required] 26: [Range(1, 100)] 27: public Decimal Price 28: { 29: get; 30: set; 31: } 32:  33: public virtual ISet<OrderDetail> Details 34: { 35: get; 36: protected set; 37: } 38:  39: [Timestamp] 40: [ScaffoldColumn(false)] 41: public Byte[] RowVersion 42: { 43: get; 44: set; 45: } 46: } Keep in mind that this is a simple scenario. Let’s see what we have: A class Product, that maps to a product record on the database; A product has a required (RequiredAttribute) Name property which can contain up to 50 characters (StringLengthAttribute); The product’s Price must be a decimal value between 1 and 100 (RangeAttribute); It contains a set of order details, for each time that it has been ordered, which we will not talk about (Details); The record’s primary key (mapped to property ProductId) comes from a SQL Server IDENTITY column generated by the database (KeyAttribute, DatabaseGeneratedAttribute); The table uses a SQL Server ROWVERSION (previously known as TIMESTAMP) column for optimistic concurrency control mapped to property RowVersion (TimestampAttribute). Then we will need a controller for viewing product details, which will located on folder ~/Controllers under the name ProductController: 1: public class ProductController : Controller 2: { 3: [HttpGet] 4: public ViewResult Get(Int32 id = 0) 5: { 6: if (id != 0) 7: { 8: using (ProductContext ctx = new ProductContext()) 9: { 10: return (this.View("Single", ctx.Products.Find(id) ?? new Product())); 11: } 12: } 13: else 14: { 15: return (this.View("Single", new Product())); 16: } 17: } 18: } If the requested product does not exist, or one was not requested at all, one with default values will be returned. I am using a view named Single to display the product’s details, more on that later. As you can see, it delegates the loading of products to an Entity Framework context, which is defined as: 1: public class ProductContext: DbContext 2: { 3: public DbSet<Product> Products 4: { 5: get; 6: set; 7: } 8: } Like I said before, I’ll keep it simple for now, only aggregate root Product is available. The controller will use the standard routes defined by the Visual Studio ASP.NET MVC 3 template: 1: routes.MapRoute( 2: "Default", // Route name 3: "{controller}/{action}/{id}", // URL with parameters 4: new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 5: ); Next, we need a view for displaying the product details, let’s call it Single, and have it located under ~/Views/Product: 1: <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<Product>" %> 2: <!DOCTYPE html> 3:  4: <html> 5: <head runat="server"> 6: <title>Product</title> 7: <script src="/Scripts/jquery-1.7.2.js" type="text/javascript"></script> 1:  2: <script src="/Scripts/jquery-ui-1.8.19.js" type="text/javascript"> 1: </script> 2: <script src="/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"> 1: </script> 2: <script src="/Scripts/jquery.validate.js" type="text/javascript"> 1: </script> 2: <script src="/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"> 1: </script> 2: <script type="text/javascript"> 3: function onFailure(error) 4: { 5: } 6:  7: function onComplete(ctx) 8: { 9: } 10:  11: </script> 8: </head> 9: <body> 10: <div> 11: <% 1: : this.Html.ValidationSummary(false) %> 12: <% 1: using (this.Ajax.BeginForm("Edit", "Product", new AjaxOptions{ HttpMethod = FormMethod.Post.ToString(), OnSuccess = "onSuccess", OnFailure = "onFailure" })) { %> 13: <% 1: : this.Html.EditorForModel() %> 14: <input type="submit" name="submit" value="Submit" /> 15: <% 1: } %> 16: </div> 17: </body> 18: </html> Yes… I am using ASPX syntax… sorry about that!   I implemented an editor template for the Product class, which must be located on the ~/Views/Shared/EditorTemplates folder as file Product.ascx: 1: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Product>" %> 2: <div> 3: <%: this.Html.HiddenFor(model => model.ProductId) %> 4: <%: this.Html.HiddenFor(model => model.RowVersion) %> 5: <fieldset> 6: <legend>Product</legend> 7: <div class="editor-label"> 8: <%: this.Html.LabelFor(model => model.Name) %> 9: </div> 10: <div class="editor-field"> 11: <%: this.Html.TextBoxFor(model => model.Name) %> 12: <%: this.Html.ValidationMessageFor(model => model.Name) %> 13: </div> 14: <div class="editor-label"> 15: <%= this.Html.LabelFor(model => model.Price) %> 16: </div> 17: <div class="editor-field"> 18: <%= this.Html.TextBoxFor(model => model.Price) %> 19: <%: this.Html.ValidationMessageFor(model => model.Price) %> 20: </div> 21: </fieldset> 22: </div> One thing you’ll notice is, I am including both the ProductId and the RowVersion properties as hidden fields; they will come handy later or, so that we know what product and version we are editing. The other thing is the included JavaScript files: jQuery, jQuery UI and unobtrusive validations. Also, I am not using the Content extension method for translating relative URLs, because that way I would lose JavaScript intellisense for jQuery functions. OK, so, at this moment, I want to add support for AJAX and optimistic concurrency control. So I write a controller method like this: 1: [HttpPost] 2: [AjaxOnly] 3: [Authorize] 4: public JsonResult Edit(Product product) 5: { 6: if (this.TryValidateModel(product) == true) 7: { 8: using (BlogContext ctx = new BlogContext()) 9: { 10: Boolean success = false; 11:  12: ctx.Entry(product).State = (product.ProductId == 0) ? EntityState.Added : EntityState.Modified; 13:  14: try 15: { 16: success = (ctx.SaveChanges() == 1); 17: } 18: catch (DbUpdateConcurrencyException) 19: { 20: ctx.Entry(product).Reload(); 21: } 22:  23: return (this.Json(new { Success = success, ProductId = product.ProductId, RowVersion = Convert.ToBase64String(product.RowVersion) })); 24: } 25: } 26: else 27: { 28: return (this.Json(new { Success = false, ProductId = 0, RowVersion = String.Empty })); 29: } 30: } So, this method is only valid for HTTP POST requests (HttpPost), coming from AJAX (AjaxOnly, from MVC Futures), and from authenticated users (Authorize). It returns a JSON object, which is what you would normally use for AJAX requests, containing three properties: Success: a boolean flag; RowVersion: the current version of the ROWVERSION column as a Base-64 string; ProductId: the inserted product id, as coming from the database. If the product is new, it will be inserted into the database, and its primary key will be returned into the ProductId property. Success will be set to true; If a DbUpdateConcurrencyException occurs, it means that the value in the RowVersion property does not match the current ROWVERSION column value on the database, so the record must have been modified between the time that the page was loaded and the time we attempted to save the product. In this case, the controller just gets the new value from the database and returns it in the JSON object; Success will be false. Otherwise, it will be updated, and Success, ProductId and RowVersion will all have their values set accordingly. So let’s see how we can react to these situations on the client side. Specifically, we want to deal with these situations: The user is not logged in when the update/create request is made, perhaps the cookie expired; The optimistic concurrency check failed; All went well. So, let’s change our view: 1: <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<Product>" %> 2: <%@ Import Namespace="System.Web.Security" %> 3:  4: <!DOCTYPE html> 5:  6: <html> 7: <head runat="server"> 8: <title>Product</title> 9: <script src="/Scripts/jquery-1.7.2.js" type="text/javascript"></script> 1:  2: <script src="/Scripts/jquery-ui-1.8.19.js" type="text/javascript"> 1: </script> 2: <script src="/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"> 1: </script> 2: <script src="/Scripts/jquery.validate.js" type="text/javascript"> 1: </script> 2: <script src="/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"> 1: </script> 2: <script type="text/javascript"> 3: function onFailure(error) 4: { 5: window.alert('An error occurred: ' + error); 6: } 7:  8: function onSuccess(ctx) 9: { 10: if (typeof (ctx.Success) != 'undefined') 11: { 12: $('input#ProductId').val(ctx.ProductId); 13: $('input#RowVersion').val(ctx.RowVersion); 14:  15: if (ctx.Success == false) 16: { 17: window.alert('An error occurred while updating the entity: it may have been modified by third parties. Please try again.'); 18: } 19: else 20: { 21: window.alert('Saved successfully'); 22: } 23: } 24: else 25: { 26: if (window.confirm('Not logged in. Login now?') == true) 27: { 28: document.location.href = '<%: FormsAuthentication.LoginUrl %>?ReturnURL=' + document.location.pathname; 29: } 30: } 31: } 32:  33: </script> 10: </head> 11: <body> 12: <div> 13: <% 1: : this.Html.ValidationSummary(false) %> 14: <% 1: using (this.Ajax.BeginForm("Edit", "Product", new AjaxOptions{ HttpMethod = FormMethod.Post.ToString(), OnSuccess = "onSuccess", OnFailure = "onFailure" })) { %> 15: <% 1: : this.Html.EditorForModel() %> 16: <input type="submit" name="submit" value="Submit" /> 17: <% 1: } %> 18: </div> 19: </body> 20: </html> The implementation of the onSuccess function first checks if the response contains a Success property, if not, the most likely cause is the request was redirected to the login page (using Forms Authentication), because it wasn’t authenticated, so we navigate there as well, keeping the reference to the current page. It then saves the current values of the ProductId and RowVersion properties to their respective hidden fields. They will be sent on each successive post and will be used in determining if the request is for adding a new product or to updating an existing one. The only thing missing is the ability to insert a new product, after inserting/editing an existing one, which can be easily achieved using this snippet: 1: <input type="button" value="New" onclick="$('input#ProductId').val('');$('input#RowVersion').val('');"/> And that’s it.

    Read the article

1