Solibulo

Uninteresting things

UpdatePanel html helper for jQuery/ASP.NET MVC

by softlion 9. July 2010 17:36

Sometimes you don’t have time to write javascript code, and if like me you don’t want to use microsoft ajax, you’ll end up creating a basic form.

 

It would be nice to have the equivalent of Ajax.BeginForm( ) but using the jQuery library.

Well now you have it.

 

 

Usage

 

Add the jquery ajaxform plugin to your site

See http://jquery.malsup.com/form/

 

In a partial control (called DemoAjaxForm here), add your form

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DemoFormModel>" %> <%@ Import Namespace="Mvc.Extensions" %> <% using(Html.UpdatePanel( "demoFormPost","home" ) ) { %> first name : <%: Html.EditorFor(m => m.FirstName) %> <%: Html.ValidationMessageFor(m => m.FirstName) %><br /> friend first name : <%: Html.EditorFor(m => m.FirstNameOfFriend) %> <%: Html.ValidationMessageFor(m => m.FirstNameOfFriend)%><br /> <br /> <% if(Model.PercentMatch.HasValue) { %> <div style="font-weight: bold; text-align: center; font-size: x-large">LOVE MATCH <%: Model.PercentMatch %>%</div> <br /> <% } %> <div><%: Html.ValidationSummary(true) %></div> <input type="submit" style="border: 1px solid #333" /> <% } %>

 

 

 

 

 

On your home controller, add this demoFormPost action

you can mark this action with [HttpPost] (you should)

 

 

        public ActionResult DemoFormPost(DemoFormModel model)
        {
            if (ModelState.IsValid)
            {
                model.FirstName.Trim();
                model.FirstNameOfFriend.Trim();
                model.CalcLoveMatch();
            }
            else
                ModelState.AddModelError("", "Fill all fields mark with a star");

            return PartialView("DemoAjaxForm", model);
        }

 

The model

    public class DemoFormModel
    {
        [Required(ErrorMessage="*")]
        [StringLength(20, ErrorMessage = "Max 20 caractères")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "*")]
        [StringLength(20, ErrorMessage = "Max 20 caractères")]
        public string FirstNameOfFriend { get; set; }

        public int? PercentMatch;


        public void CalcLoveMatch()
        {
            PercentMatch = new Random().Next(0,100);
        }

    }

 

Full code of the UpdatePanel Html helper

 

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

namespace Mvc.Extensions {

public static partial class HtmlExtensions { public static MvcUpdatePanel UpdatePanel(this HtmlHelper html, string action, string controller,

object routeValues = null, object htmlAttributes = null) { return new MvcUpdatePanel(html, action, controller, routeValues, htmlAttributes); } } public class MvcUpdatePanel : IDisposable { readonly MvcForm _form; readonly TextWriter _writer; bool _disposed; public MvcUpdatePanel(HtmlHelper html, string action, string controller, object routeValues,

object htmlAttributes) { _writer = html.ViewContext.Writer; RouteValueDictionary dicRouteValues = new RouteValueDictionary(routeValues); IDictionary<string,object> dicHtmlAttributes = new RouteValueDictionary(htmlAttributes); string formId; object oFormId; if (dicHtmlAttributes.TryGetValue("id", out oFormId)) formId = oFormId as string; else { formId = GenerateFormId(); dicHtmlAttributes.Add("id", formId); } //Render scripts RenderScripts(formId); //Render form _form = html.BeginForm(action, controller, dicRouteValues, FormMethod.Post, dicHtmlAttributes); } #region private private static string GenerateFormId() { return "mup" + new Random().Next(0, 1000000); } private void RenderScripts(string formId) { var tagBuilder = new TagBuilder("div"); tagBuilder.MergeAttribute("id", formId+"div"); _writer.Write(tagBuilder.ToString(TagRenderMode.StartTag)); tagBuilder = new TagBuilder("script"); tagBuilder.MergeAttribute("type", "text/javascript"); _writer.Write(tagBuilder.ToString(TagRenderMode.StartTag)); const string script = @" $(function(){{ $('#{0}').ajaxForm({{ target: '#{1}' }}); }});"; _writer.Write(String.Format(CultureInfo.InvariantCulture, script, formId, formId + "div")); _writer.Write(tagBuilder.ToString(TagRenderMode.EndTag)); } #endregion #region IDisposable Members /// <summary> /// Render end of form /// </summary> public void Dispose() { Dispose(true /* disposing */); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { _disposed = true; _form.Dispose(); _writer.Write("</div>"); } } #endregion }

}

Tags: