iNerd Blog

Model Binding To A List ASP.NET MVC

Posted in Programming by Ari on 15 July 2010

I was recently writing a code that requires Model Binding to a list. The problem was, I didn’t have a single clue on how to pass the complex object from view to controller.
Then i came across this blog post by Phil Haack, http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx, I scanned through the code and it is actually quite simple. It is all about naming the textbox or whatever it is you use to edit.

In my case, i have a Person class which contains a list of contact objects.


 public class Person
    {
        public string Age { get; set; }
        public string Company { get; set; }
        public List Contacts { get; set; }
    }

and within the Contact list i have multiple contact like Home Contact, Office Contact, Billing Contact etc. Now, to update all three contacts at once, we must follow this naming convention. The idea is to put all of them in one form and create something that resemble this.


<form action="/Home/Update" method="post">
<!-- Office -->
    <input name="[0].Address" type="text" value="Commonwealth" />
    <input name="[0].Country" type="text" value="Singapore" />
    <input name="[0].City" type="text" value="Singapore" />

    <!-- Home -->
    <input name="[1].Address" type="text" value="Pioneer" />
    <input name="[1].Country" type="text" value="Singapore" />
    <input name="[1].City" type="text" value="Singapore" />

<!-- Billing -->
    <input name="[2].Address" type="text" value="Lakeside" />
    <input name="[2].Country" type="text" value="Singapore" />
    <input name="[2].City" type="text" value="Singapore" />

    


Notice the [0] [1] and [2] follow by name. This can be easily achieved in ASP.NET MVC 2. see below



However since I’m doing it in MVC 1, heres how i did it. Messy but it works.


<table class="firstTable">
<tbody>
            <tr><td><label>address    <td><%= Html.TextArea("["+i.ToString()+"]."+"PrimaryStreet", data.PrimaryStreet)%> </td> </tr>
            <tr><td><label>country     <td><%= Html.TextBox("[" + i.ToString() + "]." + "PrimaryCountry", data.PrimaryCountry)%> </td> </tr>
            <tr><td><label>city       <td><%= Html.TextBox("[" + i.ToString() + "]." + "PrimaryTown", data.PrimaryTown)%> </td> </tr> 
</tbody>
</table>
<input type="submit" value="Save" />

That’s it for the view and heres the controller.


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Update(IList contact)
        {
                 ..........
        }

Alternatively we can do it with javascript. Read

Render XML-to-HTML to be included in ASP.NET MVC masterpage

Posted in Programming by Ari on 18 May 2010

Again this is not my code, original post can be found here. So in the previous post, i managed to transform from xml to html in asp.net mvc, though with that method the resulting page opens up in a new window which is not quite what i expected. With this RenderXml extension method, result page will be embedded into the master page and it looks so much better.

To do that create a static class RenderXmlExtensions, copy this code below:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using System.Web.Mvc;
using System.Web;
using System.Xml.Xsl;

namespace MvcApplication1.Controllers
{
    /// 
    /// Provides support for rendering a XML.
    /// 
    public static class RenderXmlExtensions
    {
        #region Fields
        private static XslCompiledTransform _transparentTransform;
        #endregion

        #region Constructor
        static RenderXmlExtensions()
        {
            XmlTextReader copyTransformReader = new XmlTextReader(new StringReader("   "));
            _transparentTransform = new XslCompiledTransform();
            _transparentTransform.Load(copyTransformReader);
        }
        #endregion

        #region Methods
        /// 
        /// Renders the specified XML by using the specified HMTL helper.
        /// 
        ///
The HTML helper
        ///
The XML document
        ///
The XSLT transformation
        public static void RenderXml(this HtmlHelper htmlHelper, XmlDocument xmlDocument, XslCompiledTransform transform)
        {
            RenderXmlInternal(htmlHelper, xmlDocument, null, String.Empty, transform, String.Empty, null);
        }

        /// 
        /// Renders the specified XML by using the specified HMTL helper.
        /// 
        ///
The HTML helper
        ///
The XML document
        ///
The XSLT transformation
        ///
The XSLT transformation arguments list
        public static void RenderXml(this HtmlHelper htmlHelper, XmlDocument xmlDocument, XslCompiledTransform transform, XsltArgumentList transformArgumentList)
        {
            RenderXmlInternal(htmlHelper, xmlDocument, null, String.Empty, transform, String.Empty, transformArgumentList);
        }

        /// 
        /// Renders the specified XML by using the specified HMTL helper.
        /// 
        ///
The HTML helper
        ///
The XML document
        ///
The XSLT transformation source
        public static void RenderXml(this HtmlHelper htmlHelper, XmlDocument xmlDocument, string transformSource)
        {
            RenderXmlInternal(htmlHelper, xmlDocument, null, String.Empty, null, transformSource, null);
        }

        /// 
        /// Renders the specified XML by using the specified HMTL helper.
        /// 
        ///
The HTML helper
        ///
The XML document
        ///
The XSLT transformation source
        ///
The XSLT transformation arguments list
        public static void RenderXml(this HtmlHelper htmlHelper, XmlDocument xmlDocument, string transformSource, XsltArgumentList transformArgumentList)
        {
            RenderXmlInternal(htmlHelper, xmlDocument, null, String.Empty, null, transformSource, transformArgumentList);
        }

        /// 
        /// Renders the specified XML by using the specified HMTL helper.
        /// 
        ///
The HTML helper
        ///
The XML XPath navigator
        ///
The XSLT transformation
        public static void RenderXml(this HtmlHelper htmlHelper, XPathNavigator xpathNavigator, XslCompiledTransform transform)
        {
            RenderXmlInternal(htmlHelper, null, xpathNavigator, String.Empty, transform, String.Empty, null);
        }

        /// 
        /// Renders the specified XML by using the specified HMTL helper.
        /// 
        ///
The HTML helper
        ///
The XML XPath navigator
        ///
The XSLT transformation
        ///
The XSLT transformation arguments list
        public static void RenderXml(this HtmlHelper htmlHelper, XPathNavigator xpathNavigator, XslCompiledTransform transform, XsltArgumentList transformArgumentList)
        {
            RenderXmlInternal(htmlHelper, null, xpathNavigator, String.Empty, transform, String.Empty, transformArgumentList);
        }

        /// 
        /// Renders the specified XML by using the specified HMTL helper.
        /// 
        ///
The HTML helper
        ///
The XML XPath navigator
        ///
The XSLT transformation source
        public static void RenderXml(this HtmlHelper htmlHelper, XPathNavigator xpathNavigator, string transformSource)
        {
            RenderXmlInternal(htmlHelper, null, xpathNavigator, String.Empty, null, transformSource, null);
        }

        /// 
        /// Renders the specified XML by using the specified HMTL helper.
        /// 
        ///
The HTML helper
        ///
The XML XPath navigator
        ///
The XSLT transformation source
        ///
The XSLT transformation arguments list
        public static void RenderXml(this HtmlHelper htmlHelper, XPathNavigator xpathNavigator, string transformSource, XsltArgumentList transformArgumentList)
        {
            RenderXmlInternal(htmlHelper, null, xpathNavigator, String.Empty, null, transformSource, transformArgumentList);
        }

        /// 
        /// Renders the specified XML by using the specified HMTL helper.
        /// 
        ///
The HTML helper
        ///
The XML path
        ///
The XSLT transformation
        public static void RenderXml(this HtmlHelper htmlHelper, string documentSource, XslCompiledTransform transform)
        {
            RenderXmlInternal(htmlHelper, null, null, documentSource, transform, String.Empty, null);
        }

        /// 
        /// Renders the specified XML by using the specified HMTL helper.
        /// 
        ///
The HTML helper
        ///
The XML path
        ///
The XSLT transformation
        ///
The XSLT transformation arguments list
        public static void RenderXml(this HtmlHelper htmlHelper, string documentSource, XslCompiledTransform transform, XsltArgumentList transformArgumentList)
        {
            RenderXmlInternal(htmlHelper, null, null, documentSource, transform, String.Empty, transformArgumentList);
        }

        /// 
        /// Renders the specified XML by using the specified HMTL helper.
        /// 
        ///
The HTML helper
        ///
The XML path
        ///
The XSLT transformation source
        public static void RenderXml(this HtmlHelper htmlHelper, string documentSource, string transformSource)
        {
            RenderXmlInternal(htmlHelper, null, null, documentSource, null, transformSource, null);
        }

        /// 
        /// Renders the specified XML by using the specified HMTL helper.
        /// 
        ///
The HTML helper
        ///
The XML path
        ///
The XSLT transformation source
        ///
The XSLT transformation arguments list
        public static void RenderXml(this HtmlHelper htmlHelper, string documentSource, string transformSource, XsltArgumentList transformArgumentList)
        {
            RenderXmlInternal(htmlHelper, null, null, documentSource, null, transformSource, transformArgumentList);
        }

        private static void RenderXmlInternal(HtmlHelper htmlHelper, XmlDocument xmlDocument, XPathNavigator xpathNavigator, string documentSource, XslCompiledTransform transform, string transformSource, XsltArgumentList transformArgumentList)
        {
            XPathDocument xpathDocument = null;
            //Checking if we have been given XmlDocument or XPathNavigator directly, or do we have path for document
            if ((xmlDocument == null) && (xpathNavigator == null) && (!String.IsNullOrEmpty(documentSource) && (documentSource.Trim().Length != 0)))
            {
                //Checking if path is absolute or relative
                if (!Path.IsPathRooted(documentSource))
                    //Mapping the relative path
                    documentSource = htmlHelper.ViewContext.HttpContext.Server.MapPath(documentSource);

                //Loading XML from file into XPathDocument
                using (FileStream documentStream = new FileStream(documentSource, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    XmlTextReader documentReader = new XmlTextReader(documentStream);
                    xpathDocument = new XPathDocument(documentReader);
                }
            }

            //Checking if we have been given XslCompiledTransform directly, or do we have path for transform
            if ((transform == null) && (!String.IsNullOrEmpty(transformSource) && (transformSource.Trim().Length != 0)))
            {
                //Checking if path is absolute or relative
                if (!Path.IsPathRooted(transformSource))
                    //Mapping the relative path
                    transformSource = htmlHelper.ViewContext.HttpContext.Server.MapPath(transformSource);

                //Loading XSLT from file into XslCompiledTransform
                using (FileStream transformStream = new FileStream(transformSource, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    XmlTextReader tranformReader = new XmlTextReader(transformStream);
                    transform = new XslCompiledTransform();
                    transform.Load(tranformReader);
                }
            }

            //Checking if we have XML in any form
            if (((xmlDocument != null) || (xpathDocument != null)) || (xpathNavigator != null))
            {
                //Checking if we have XSLT
                if (transform == null)
                    //If not, let's use transparent one
                    transform = _transparentTransform;

                //Perform transformation based on form in which we have our XML
                if (xmlDocument != null)
                    transform.Transform((IXPathNavigable)xmlDocument, transformArgumentList, htmlHelper.ViewContext.HttpContext.Response.Output);
                else if (xpathNavigator != null)
                    transform.Transform(xpathNavigator, transformArgumentList, htmlHelper.ViewContext.HttpContext.Response.Output);
                else
                    transform.Transform((IXPathNavigable)xpathDocument, transformArgumentList, htmlHelper.ViewContext.HttpContext.Response.Output);
            }
        }
        #endregion
    }
}

In the controller prepare an action method, which will pass our XML to view

   public ActionResult RenderXml()
        {
            XmlDocument cdCatalogDocument = new XmlDocument();
            cdCatalogDocument.Load(Server.MapPath("~/App_Data/cdcatalog.xml"));
            return View(cdCatalogDocument);
        }

And finally call the RenderXml extension method in the contentholder

   <%  Html.RenderXml((System.Xml.XmlDocument)Model, "~/App_Data/cdcatalog.xsl"); %>

Xml-to-Html with XSLT in ASP.NET MVC

Posted in Programming by Ari on 18 May 2010

This is how you write an XML-to-HTML custom actionresult using XSLT , in ASP.NET MVC. Code is not originally mine. Just copy everything and it should work.
So create a helper class and name it XmlActionresult and follow exactly as bellow.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
using System.Xml.XPath;

namespace MvcApplication1.Controllers
{
    public class XmlActionResult :ActionResult
    {
     #region Fields
        private XmlDocument _xmlDocument;
        private XPathNavigator _xpathNavigator;
        private string _documentContent;
        private string _documentSource;
        private XslCompiledTransform _transform;
        private static XslCompiledTransform _transparentTransform;
        private string _transformSource;
        private XsltArgumentList _transformArgumentList;
        #endregion

        #region Properties
        /// 
        /// Gets or sets the XmlDocument to write to the response.
        /// 
        public XmlDocument Document
        {
            get { return _xmlDocument; }
            set
            {
                _xmlDocument = value;
                _documentContent = String.Empty;
                _documentSource = String.Empty;
                _xpathNavigator = null;
            }
        }

        /// 
        /// Gets or sets a string that contains the XML document to write to the response.
        /// 
        public string DocumentContent
        {
            get { return _documentContent; }
            set
            {
                _xmlDocument = null;
                _documentContent = value;
                _documentSource = String.Empty;
                _xpathNavigator = null;
            }
        }

        /// 
        /// Gets or sets the path to an XML document to write to the response.
        /// 
        public string DocumentSource
        {
            get { return _documentSource; }
            set
            {
                _xmlDocument = null;
                _documentContent = String.Empty;
                _documentSource = value;
                _xpathNavigator = null;
            }
        }

        /// 
        /// Gets or sets the XslCompiledTransform object that formats the XML document before it is written to the response.
        /// 
        public XslCompiledTransform Transform
        {
            get { return _transform; }
            set
            {
                _transform = value;
                _transformSource = String.Empty;
            }
        }

        /// 
        /// Gets or sets a XsltArgumentList that contains a list of optional arguments passed to the style sheet and used during the XSL transformation.
        /// 
        public XsltArgumentList TransformArgumentList
        {
            get { return _transformArgumentList; }
            set { _transformArgumentList = value; }
        }

        /// 
        /// Gets or sets the path to an XSL Transformation style sheet that formats the XML document before it is written to the response.
        /// 
        public string TransformSource
        {
            get { return _transformSource; }
            set
            {
                _transform = null;
                _transformSource = value;
            }
        }

        /// 
        /// Gets or sets a cursor model for navigating and editing the XML data to write to the response.
        /// 
        public XPathNavigator XPathNavigator
        {
            get { return _xpathNavigator; }
            set
            {
                _xmlDocument = null;
                _documentContent = String.Empty;
                _documentSource = String.Empty;
                _xpathNavigator = value;
            }
        }
        #endregion

        #region Constructor
        static XmlActionResult()
        {
            XmlTextReader copyTransformReader = new XmlTextReader(new StringReader("   "));
            _transparentTransform = new XslCompiledTransform();
            _transparentTransform.Load(copyTransformReader);
        }
        #endregion

        #region Methods
        public override void ExecuteResult(ControllerContext context)
        {
            XPathDocument xpathDocument = null;
            //Checking if we have been given XmlDocument or XPathNavigator directly
            if ((_xmlDocument == null) && (_xpathNavigator == null))
            {
                //Checking if we have document content
                if (!String.IsNullOrEmpty(_documentContent))
                {
                    StringReader documentReader = new StringReader(_documentContent);
                    xpathDocument = new XPathDocument(documentReader);
                }
                //Checking if we have path for document
                else if (!String.IsNullOrEmpty(_documentSource) && (_documentSource.Trim().Length != 0))
                {
                    //Checking if path is absolute or relative
                    if (!Path.IsPathRooted(_documentSource))
                        //Mapping the relative path
                        _documentSource = context.HttpContext.Server.MapPath(_documentSource);

                    //Loading XML from file into XPathDocument
                    using (FileStream documentStream = new FileStream(_documentSource, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        XmlTextReader documentReader = new XmlTextReader(documentStream);
                        xpathDocument = new XPathDocument(documentReader);
                    }
                }
            }

            //Checking if we have been given XslCompiledTransform directly, or do we have path for transform
            if ((_transform == null) && (!String.IsNullOrEmpty(_transformSource) && (_transformSource.Trim().Length != 0)))
            {
                //Checking if path is absolute or relative
                if (!Path.IsPathRooted(_transformSource))
                    //Mapping the relative path
                    _transformSource = context.HttpContext.Server.MapPath(_transformSource);

                //Loading XSLT from file into XslCompiledTransform
                using (FileStream transformStream = new FileStream(_transformSource, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    XmlTextReader tranformReader = new XmlTextReader(transformStream);
                    _transform = new XslCompiledTransform();
                    _transform.Load(tranformReader);
                }
            }

            //Checking if we have XML in any form
            if (((_xmlDocument != null) || (xpathDocument != null)) || (_xpathNavigator != null))
            {
                context.HttpContext.Response.ContentType = "text/html";

                //Checking if we have XSLT
                if (_transform == null)
                    //If not, let's use transparent one
                    _transform = _transparentTransform;

                //Perform transformation based on form in which we have our XML
                if (_xmlDocument != null)
                    _transform.Transform((IXPathNavigable)_xmlDocument, _transformArgumentList, context.HttpContext.Response.Output);
                else if (_xpathNavigator != null)
                    _transform.Transform(_xpathNavigator, _transformArgumentList, context.HttpContext.Response.Output);
                else
                    _transform.Transform((IXPathNavigable)xpathDocument, _transformArgumentList, context.HttpContext.Response.Output);
            }
        }
        #endregion
    }
}


Next on your controller:

 public XmlActionResult Test()
        {
            XmlDocument cdCatalogDocument = new XmlDocument();
            cdCatalogDocument.Load(Server.MapPath("~/App_Data/cdcatalog.xml"));

            XmlActionResult result = new XmlActionResult();
            result.Document = cdCatalogDocument;
            result.TransformSource = Server.MapPath("~/App_Data/cdcatalog.xsl");
            return result;
        }

ASP.NET MVC Useful Sites

Posted in Programming by Ari on 9 April 2010

Here are some useful sites that i would love to refer back to in the future ( coz I forget things sometimes):

Regular Expression Library

Regular Expressions Library

Validation Application Block (Ms validation Framework)

http://msdn.microsoft.com/en-us/library/dd203099.aspx

ASP.NET MVC tutorials

Contact Management System

Scott Gu MVC Store

CSS Stuff

CSS tricks

— will soon be updated when i have the time. A lot more coming!

Image link in ASP.NET MVC

Posted in Programming by Ari on 9 April 2010
<td>
    <%= Html.ActionLink("Edit", "Edit", new { id=item.Id  }) %> |
    <%= Html.ActionLink("Delete", "Delete", new { id=item.Id  }) %>
</td>

This is how a normal link usually written. When you want a url to be embedded within an image it should be written like this:

<td>
   <a href='<%= Url.Action("Edit", new {id=item.Id}) %>'>
       <img src="../../Content/Edit.png" alt="Edit" /></a>
</td>
<td>
   <a href='<%= Url.Action("Delete", new {id=item.Id}) %>'>
       <img src="../../Content/Delete.png" alt="Delete" /></a>

</td>


	
Tagged with: