Friday, June 22, 2012

MVC knowledge

1. Custom Helper
Create a new Class and use the following code
public static class MyHtmlHelper
    public static MvcHtmlString Image(this HtmlHelper helper, string src, string altText)
        var builder = new TagBuilder("img");
        builder.MergeAttribute("src", src);
        builder.MergeAttribute("alt", altText);
        return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
In cshtml layout page, add @using namespace on the top, the use @Html.Image(src, altText) at any place.

If we need to use this method in any layout pages, we should open the web.config file which is under Views folder, add <add namespace="namespace"/> in <namespce> block.

2. Custom Validation
There are two ways to custom the validation. The first one is custom attributes, the second one is use IValidatableObject interface.

Make the model inherits from the IValidatableObject interface, and then implement it. Such as
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    // Write your custom validation code here and then
    yield return new ValidationResult("error message", new[] { "fields that against the validation" });

In this way, the error message will be displayed behind the fields.

3. Quick add script link
Create the following code in your cshtml layout page,
@helper Script(string scriptName)
    <script src="@Url.Content("~/Scripts/" + scriptName)" type="text/javascript" />

Then you can use it in your layout page, like @Script("jquery.min.js")
Note: this script method is only available in current layout page, if you want it to be available in any layout pages, you either create a custom helper in C# code or do the following things.

Create a App_Code folder under this Mvc project, create a new MVC view page with name "Content", delete all content in that file, and then type the following code

using System.Web.Mvc;
@helper Script(string scriptName, UrlHelper url)
    <script src="@url.Content("~/Scripts/" + scriptName)" type="text/javascript" />

Then you can use it in any layout pages, like @Content.Script("jquery.min.js", Url)

No comments:

Post a Comment