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>

inline asp.net tags... sorting them all out (<%$, <%=, <%, <%#, etc.)

by naspinski 2/22/2012 9:55:00 AM

There are all sorts of different inline tags, and I haven't found a place that explains them all in one place, so here is the quick and dirty...

*UDPATED 2012-02-22: Thanks to Conrad Buck and Austin for updates!

<% ... %>

The most basic inline tag, basically runs normal code: 

<% if (User.IsInRole("admin")) { %>
    You can see this
<% } else { %>
    You are no admin fool!
<%} %>

http://msdn2.microsoft.com/en-us/library/ms178135(vs.80).aspx

 

 

<%= ... %>

Used for small chunks of information, usually from objects and single pieces of information like a single string or int variable: 

The Date is now <%= DateTime.Now.ToShortDateString() %>
The value of string1 is <%= string1 %> 

http://msdn2.microsoft.com/en-us/library/6dwsdcf5(VS.71).aspx

*note: <%= is the equivalent of Response.Write() -  Courtesy of Adam from the US,thanks!

 

 

<%# .. %>

Used for Binding Expressions; such as Eval and Bind, most often found in data controls like GridView, Repeater, etc.:

<asp:Repeater ID="rptMeetings" DataSourceID="meetings" 
    runat="server">
    <ItemTemplate>
        <%# Eval("MeetingName")%>
    </ItemTemplate>
</asp:Repeater>

http://msdn2.microsoft.com/en-us/library/ms178366.aspx

 

 

<%$ ... %>

Used for expressions, not code; often seen with DataSources: 

<asp:SqlDataSource ID="party" runat="server" 
    ConnectionString="<%$ ConnectionStrings:letsParty %>" 
    SelectCommand="SELECT * FROM [table]"
/>

http://msdn2.microsoft.com/en-us/library/d5bd1tad.aspx

 

 

<%@ ... %>

This is for directive syntax; basically the stuff you see at the top your your aspx pages like control registration and page declaration: 

<%@ Page Language="C#" 
    MasterPageFile="~/MasterPage.master" 
    AutoEventWireup="true" CodeFile="Default.aspx.cs" 
    Inherits="_Default" Title="Untitled Page" %>
<%@ Register TagPrefix="wp" Namespace="CustomWebParts" %>

http://msdn2.microsoft.com/en-us/library/xz702w3e(VS.80).aspx

 

 

<%-- ... --%>

This is a server side comment, stuff you don't want anyone without code access to see:

<asp:Label ID="lblAwesome" runat="server"/>
<%-- sometimes end users make me angry --%>
<asp:LinkButton ID="lbEdit" Text="Edit" OnClick="Edit_Click" runat="server" />

http://msdn2.microsoft.com/en-us/library/4acf8afk.aspx

 

<%: ... %>

This tag is identical to the "<%= ... %>" tag except that it auto-html-encodes the value within the tag. As Phil Haack said: I often tell people it’s <%= but with the = seen from the front.:


<%: Html.TextBox("FirstName") %>

http://haacked.com/archive/2009/09/25/html-encoding-code-nuggets.aspx

 

And that's that.  

kick it on DotNetKicks.com

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.