ITmeze - IT world server like cyprus meze

Recent blog posts Tagged 'asp-net-mvc'

Validate max file size during upload in mvc


Just a quick sketch. Validation is done as an Attribute (DataAnotations way).
 public class FileAttribute : ValidationAttribute {

        public int MaxContentLength = int.MaxValue;
        public string[] AllowedFileExtensions;
        public string[] AllowedContentTypes;

        public override bool IsValid(object value) {

            var file = value as HttpPostedFileBase;

            //this should be handled by [Required]
            if (file == null)
                return true;

            if (file.ContentLength > MaxContentLength) {
                ErrorMessage = "File is too large, maximum allowed is: {0} KB".FormatWith(MaxContentLength / 1024);
                return false;

            if (AllowedFileExtensions != null) {
                if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.')))) {
                    ErrorMessage = "Please upload file of type: " + string.Join(", ", AllowedFileExtensions);
                    return false;

            if (AllowedContentTypes != null) {
                if (!AllowedContentTypes.Contains(file.ContentType)) {
                    ErrorMessage = "Please upload file of type: " + string.Join(", ", AllowedContentTypes);
                    return false;

            return true;
And now decorators (within viewmodel).
[Display(Name = "Upload Proof of Address")]
[File(AllowedFileExtensions = new string[] { ".jpg", ".gif", ".tiff", ".png", ".pdf" }, MaxContentLength = 1024 * 1024 * 8, ErrorMessage = "Invalid File")]
public HttpPostedFileBase AddressProof { get; set; }
Hope that helps someone.

Tags: [] [data-annotations] [validation] [web development]

Client side validation after Ajax Partial View result in ASP.NET MVC 3


Now, as ASP.NET MVC 3 beta was finally released I have decided to give it a try. The most exciting thing that I have noticed is implementation of an idea of so called Unobtrusive JavaScript. This is for both Ajax helpers and Client Validation. And I have to admit that I just love it. I wll just copy and paste text from scottgu blog:
Unobtrusive JavaScript and HTML 5: The AJAX and Validation helpers in ASP.NET MVC now both use an unobtrusive JavaScript approach by default. Unobtrusive JavaScript avoid injecting inline JavaScript into HTML, and instead enables cleaner separation of behavior using the new HTML 5 data- convention (which conveniently works on older browsers as well). This makes your HTML smaller and cleaner, and makes it easier to optionally swap out or customize JS libraries.  The Validation helpers in ASP.NET MVC 3 also now use the jQueryValidate plugin by default.
Basically we get all the validation done by loading js function parsing loaded DOM searching for specific parameters based on which validation rules are applied to elements. And all of that without a single js line from 'our' - web developers side. One thing is not obvious though and it certainly needs extra explanation: what happens after part of the page is loaded via Ajax request (common Partial View result). Validation is not turned for those elements although all attributes are correctly marked. I have dig a little and found within JavaScript file 'jquery.validate.unobtrusive.js' function: jQuery.validator.unobtrusive.parse(selector). Calling function after new content is loaded solves problem, like in the example below:

$.post("test/updateCustomer", { name: "Mark", surname: "Barker" },

Hope it helps someone...

Tags: [] [client side validation] [jquery] [unobtrusive javascript] [web development]

Getting ugly with BeginActionLink helper!


Have You ever had such a moment when the most stupid and trivial solution turns out to be the ONLY ONE that is logically suitable at the moment? When I had such a feeling today.... I am working on a module for one of huge web portals (not to mention which one). Part of that module is only accessible to users with administration permissions - as typical as it can be. The reason why I am mentioning that is to highlight the fact that at this specific part performance does not matter so much. Anyway, my talk to one of designers (Friday, half an hour before 'the beginning of the weekend'): Designer: I am going to spend whole weekend on those Views... Me: Yeah... S*** happens.... Designer: Those 'Html.ActionLink' that You use everywhere, how do I put something inside, you know, images, spans, staff like that... Me: Argh... Hm..... I suddenly realize that before I leave the office this guy needs an extension method: BeginActionLink like right now!. The similar one that is used for Forms elements (BeginForm). Then I started to code... Have You ever realized that ActionLink has roughly 12 overloads!!!! That would take hours to prepare BeginActionLink for most of them. idea bulb When You are blocked, what You do? Me too, I started 'googling'. Nothing simple and smart enough. Except 200 lines of code with tons of overloads... argh... But then, completely unexpectedly .... My moment of genius! Don't laugh! For people over ... some age ... that things do not happen offen! :) There are solutions that developers are ashamed of, but they simply do their job:
public static string TrimEndTag(this MvcHtmlString htmlString, string tagName = "a")
            var endTag = new TagBuilder(tagName).ToString(TagRenderMode.EndTag); 

            var tagString = htmlString.ToString();

            var endTagIndex = tagString.LastIndexOf(endTag);

            if(endTagIndex > 0)
                tagString = tagString.Remove(endTagIndex).TrimEnd();

            return tagString;

        public static string ToEndTag(this HtmlHelper html, string tagName)
            return new TagBuilder(tagName).ToString(TagRenderMode.EndTag);
I am simply removing end tag from ActionLink returned string! As simple as that! So all that is left for my buddy to do is to use it like that:
<%= Html.ActionLink(" ", "testAction", "testController", new { id = 4 }, new {}).TrimEndTag() %>

        images, spans, text, whatever...

    <%= Html.ToEndTag("a") %>
Wuala! Ugly, So ugly, but at the same time I am preserving original methods for ActionLinks and I couldn't figure out better solution....

Tags: [actionlink] [] [htmlhelpers] [web] [web development]

Copyright 2013 © ITmeze