loads of useful information, examples and tutorials pertaining to web development utilizing asp.net, c#, vb, css, xhtml, javascript, sql, xml, ajax and everything else...

 



Advertise Here
C-Sharpener.com - Programming is Easy!  Learn Asp.Net & C# in just days, Guaranteed!

Double Input problem with CheckBoxFor in MVC while serializing

by naspinski 1/25/2013 2:44:00 PM

if you have tried to serialize a CheckBoxFor from MVC to JSON, you will notice that you get two inputs, and it can mess up the data you are sending

It's no surprise that JavaScript is not sure how MVC works so when you try data.serialize() on MVC form data, you get odd results. Here is a simple workaround for when you need something to be serialized. I modified the GetPropertyName method from this post on StackOverflow.
public static string GetPropertyName<TModel, TValue>
    (Expression> exp)
{
    MemberExpression body = exp.Body as MemberExpression;
    if (body == null)
    {
        UnaryExpression ubody = (UnaryExpression)exp.Body;
        body = ubody.Operand as MemberExpression;
    }
    return body.Member.Name;
}

public static MvcHtmlString CheckBoxForJson<
    ;TModel, TValue>(this HtmlHelper<TModel> helper, 
    Expression<Func<TModel, TValue>> expression)
{
    string propName = GetPropertyName(expression);
    string html = "<input type=\"checkbox\" name=\"" 
        + propName + "\" id=\"" 
        + propName + "\" value=\"true\" />";
    return MvcHtmlString.Create(html);
}

And use it like this:
@Html.CheckBoxForJson(x => x.SomeBool)

The reason for the 'true' is because otherwise it will always pass as false since 'on' is not a bool value (html default).

MVC Html Helper for including an Id with a DisplayFor

by naspinski 10/18/2012 5:29:00 PM

there are cases when you want to include an id with your DisplayFor()

public static MvcHtmlString DisplayWithIdFor(
    this HtmlHelper helper, 
    Expression> expression, 
    string wrapperTag = "div")
{
    var id = helper.ViewContext.ViewData.TemplateInfo
        .GetFullHtmlFieldId(ExpressionHelper
            .GetExpressionText(expression));
    return MvcHtmlString.Create(
        string.Format("<{0} id=\"{1}\">{2}", wrapperTag, 
        id, helper.DisplayFor(expression)));
}

It is used like this:
@Html.DisplayWithIdFor(x => x.Name)
<!-- to produce -->
<div id="Name">Bill</div>

Or if you want to wrap it in a non-div:
@Html.DisplayWithIdFor(x => x.Name, "span")
<!-- to produce: -->
<span id="Name">Bill</span>

Using a Custom Controller Class in Asp.Net MVC to Simplify Coding

by naspinski 12/15/2011 1:23:00 PM

Controllers often have some repetitive code, implementing your own Controller class can help eliminate a lot of this

Here is a small snippet and how I use some simple tricks to help clean up my Controllers in Asp.Net MVC (using MVC 4 at the moment):
public class MyController : Controller
{
    public MyEntities Db { get; set; }

    protected override void OnActionExecuting(
        ActionExecutingContext filterContext)
    {
        if (filterContext.IsChildAction)
            return;
        this.Db = new MyEntities();
        base.OnActionExecuting(filterContext);
    }

    [HttpPost]
    public ActionResult Index(FormCollection form)
    {
        string srch = form["Search"] ?? string.Empty;
        return RedirectToAction("Index", 
            new { search = srch });
    }

    protected void AttachToDb(EntityObject obj, 
        bool save = false, string entityKeyField = "Id")
    {
            obj.EntityKey = new EntityKey(
                obj.ToPluralizedString(), entityKeyField, 
                obj.GetType().GetProperty("Id")
                .GetValue(obj, null));
            Db.Attach(obj);
            Db.ObjectStateManager.ChangeObjectState(
                obj, System.Data.EntityState.Modified);
            if (save) Db.SaveChanges();
    }
}

The first thing in the code is simple declaration of an EntityContext - this is implemented directly, but could (and usually should) be implemented differently for dependency injection, but you get the idea. Here is where I also like to include stuff that is often used and could be vital (and centralized) for an application like an output type for web services (JSON, XML, etc.).

Next the OnActionExecuting is over-ridden and the Context is initialized. Here is where you can initialize the properties you set above.

The next method, the HttpPost Index method is just an example of how often times you can consolidate a commonly used method. For this example, it was from an application that had searches on all index pages. Instead of repeating this code in every controller, you can just put it here.

The final method has become very useful. A use I often find, is when taking in a large model after an Asp.Net MVC POST event, I can attach the model to the Db generically without any extra work

This method is a bit confusing, but it is simply attaching the new model to the Db without a Db lookup. In my tables, I generally have a field 'Id' that houses the Primary Key of every table, whether it is an Int or Guid. This way, I can simply pass in whatever object I am currently working with, and by using the pluralize method, and reflection, the method can figure out which table to attach the model to - eliminating the need for me to do extra coding. Alternatively, if I want to change the Key from 'Id', I can pass that in as well.

Now when I get a model being POSTed, it is easy to deal with:
[HttpPost]
public ActionResult Edit(Widget model)
{
    if(ModelState.IsValid)
    {
        AttachToDb(model, true);
        //do stuff
    }
    else { /*do other stuff*/ }
}

This avoids the need to take another trip to the DB, change the properties on the object, then submit - streamlining the process very much and cutting down a lot of code.

This would be an example of how this would be done manually with the normal Controller class:
[HttpPost]
public ActionResult Edit(Widget model)
{
    if(ModelState.IsValid)
    {
        MyEntities db = new MyEntities();
        Widget w = db.Widgets.Single(x => x.Id == model.Id);
        w.Name = model.Name;
        w.Serial = model.Serial;
        db.SaveChanges();
        //do stuff
    }
    else { /*do other stuff*/ }
}

Not a huge difference when you are just getting 2 values, but you could see how a model with 20 or 30 fields can be cut down from 30+ lines to just 1 or 2.

Constraining Routes in MVC to an Enum the Easy Way

by naspinski 10/6/2011 5:40:00 PM

simple way to constrain a route to only allow enum values

Say I have the following enum:
public enum SearchType { Facilities, Courses, Exercises};

And I only want those the be available in route Search/{SearchType}. I could constrain it manually with a string, but then what if the enum changes and I have this in a bunch of routes? Here is a simple way to accomplish this constraint:
public static void RegisterRoutes(RouteCollection routes)
{
    List searchTypeL = new List();
    foreach (Enums.SearchType type in 
        Enum.GetValues(typeof(Enums.SearchType))) 
    { searchTypeL.Add(type.ToString()); }
    string searchTypes = string.Join("|", searchTypeL);
    
    routes.MapRoute(
        "Searches",
        "Search/{type}",
        new { controller = "Search", action = "Index" },
        new { type = searchTypes }
    )
    ...

Very basic, all this does is enumerate through your enum and create a simple string to filter with.

ReCaptcha - Getting the Challenge Key and/or image with Asp.Net MVC

by naspinski 8/1/2011 11:30:00 AM

Often times you do not need the whole deal, or you are working with a technology that doesn't employ javascript or iframes

Recently I was working on a project that needed to provide (via MVC 3) the ReCaptcha image and/or challenge key only, and not the whole html/javascript portion due to limitations by the data consumer. It took me a while, but there is quite an elegant and simple solution to this.

Here is the controller I came up with:
public class CaptchaController : Controller
{
    public string contentReturnType = "text/plain";
    public string googleChallengeUrl = "http://
        www.google.com/recaptcha/api/challenge?k={0}";
    public string googleImageUrl = "http://
        www.google.com/recaptcha/api/image?c={0}";
    public string googleImageHtml = "<img style=
        \"display: block; \" height=\"57\" width=\"300\" 
         src=\"{0}\"/>";

    [HttpGet]
    public ContentResult GetChallengeKey(
        string proxyIpAndPort = null)
    {
        string http = string.Format(googleChallengeUrl, 
            ReCaptchaValues.PublicKey);
        WebClient client = new WebClient();

        //assuming no proxy on a local machine
        if (!string.IsNullOrEmpty(proxyIpAndPort) && 
            !Request.IsLocal) 
        {
            client.Proxy = 
                new WebProxy(proxyIpAndPort, true);
        }

        string html = client.DownloadString(http);
        int start = html.IndexOf('{');
        int length = html.IndexOf('}') - start + 1;
        string json = html.Substring(start, length);

        ReCaptchaState state = 
            new JavaScriptSerializer()
                .Deserialize(json);
        return this.Content(state.challenge, 
            contentReturnType);
    }

    [HttpGet]
    public ContentResult GetImageUrl()
    {
        return this.Content(string.Format(googleImageUrl, 
            GetChallengeKey().Content), contentReturnType);
    }

    [HttpGet]
    public ContentResult GetImageHtml()
    {
        return this.Content(string.Format(googleImageHtml, 
            GetImageUrl().Content), contentReturnType);
    }
}

This is using json deserializing of the ReCaptcha return string into a .Net object named ReCaptchaState which is covered here.

Now all that you need to do is call one of the urls to get the desired result in a plaintext format (you can change the output if you wish).