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!

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

Currently rated 2.7 by 570 people

  • Currently 2.661403/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

asp.net

Helper Methods for Validating Generated Linq-to-Entities edmx Files using Partial Classes

by naspinski 2/7/2012 12:48:00 AM

Centralized client and server side validation as well as property and method additions to auto-generated classes

Say I have an auto-generated Widget class (from a database, generated into a .edmx file):
namespace My.NameSpace
{
    public partial class Widget
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Now I want to add some methods and validation to the class, but I do not want to edit the class directly. What I need to do is make a partial class and add the things in there. This accomplished two things: 1. separates logic from structure and 2. separates the files so another auto-generation or update will not lose the work you do. This is very simple to do, here is an example:
// be SURE that it is in the same namespace
namespace My.NameSpace
{
    //System.ComponentModel.DataAnnotations
    [MetadataType(typeof(VWidget))]
    public partial class Widget
    {
        // I want to add another property
        public string FullName
        { get { return Name + Id; } }
    }

    // this is the validation segment
    // this is the same as the class name above
    public class VWidget
    {
        [Display(Name = "Widget Name")]
        [Required]
        [StringLength(50)]
        public string Name { get; set; }
    }
}

Now this was very simple, but it shows how to add this in. First of all, there is a new property to Widget called 'FullName' which will combine the 'Name' and 'Id' properties. Not really all that useful, but you can see how it is used.

The next part is really cool, you can put all of your validation in the 'VWidget' class (name doesn't really matter here). Here you can see that 'Name' is now required, has a max length of 50 characters, and a label will display "Widget Name" instead of the default property name. This way, if you are using this library with MVC, you can do something this simple:
@using (Html.BeginForm())
{ 
    @Html.ValidationSummary()
    @Html.LabelFor(x => x.Name)
    @Html.EditorFor(x => x.Name)
}

And you will be pushing client-side validation as well as a centralized area to hold your custom labels. On top of that, in your code, if you simply include:
if (ModelState.IsValid)

You will be enforcing server-side validation as well.

Later I will get into how you can use .resx files for localization and centralization along with these partial classes.

Currently rated 1.6 by 80 people

  • Currently 1.625/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

c# | steal some code

Ternary Operator in SQL

by naspinski 2/3/2012 1:32:00 PM

there technically isn't one, but an equivalent isn't too hard to do

This ternary in C#:
(str.Length > 0 ? "yes" : "no");

Is equivalent to this in SQL:
(CASE WHEN LEN(@str) > 0 THEN "yes" ELSE "no" END);

Currently rated 1.9 by 35 people

  • Currently 1.914286/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

sql

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.

Currently rated 2.5 by 39 people

  • Currently 2.48718/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

asp.net | c# | mvc | steal some code