Add css class attribute to html helpers in asp.NET MVC 2
August 26, 2010
It took me forever to find out how to do this so hoping this will save someone else the time.
Here is an example:
<%= Html.TextBoxFor(model => model.Email, new { @class = "txtLarge" })%>
In asp.NET MVC I used _class it seems in MVC 2 you need to use the @ symbol.
asp.net MVC 2 Validation – One Field Required
June 11, 2010
I was building a form that had two fields: home phone number and mobile phone number.
The client needed at least one of the two fields filled out.
Given the existing DataAnnotations nothing fit the bill in this case. I ended up creating a custom validation attribute that is applied at the class level.
I based it off of the PropertiesMustMatchAttribute custom attribute that is included in the AccountModels.cs/vb file within the default ASP.NET MVC 2 application project template (just do a File->New ASP.NET MVC 2 Web Project within VS 2010 and look for this class).
First off in the ContactModel.cs I added:
using System.ComponentModel.DataAnnotations; using System.Globalization;
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class OneOrOtherFieldRequired : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' or '{1}' are required.";
private readonly object _typeId = new object();
public OneOrOtherFieldRequired(string field1, string field2)
: base(_defaultErrorMessage)
{
Field1 = field1;
Field2 = field2;
}
public string Field1 { get; private set; }
public string Field2 { get; private set; }
public override object TypeId
{
get
{
return _typeId;
}
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, Field1, Field2);
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
object field1 = properties.Find(Field1, true).GetValue(value);
object field2 = properties.Find(Field2, true).GetValue(value);
string valueAsString1 = field1 as string;
string valueAsString2 = field2 as string;
if (String.IsNullOrEmpty(valueAsString1) && String.IsNullOrEmpty(valueAsString2))
{
return false;
}
return true;
}
}
I then created in ContactModel.cs the ContactModel class. In this class I have among other properties the two phone number properies: HomePhoneNumber and MobilePhoneNumber.
[OneOrOtherFieldRequired("HomePhone", "MobilePhone", ErrorMessage="Please fill in either your home or mobile number.")]
public class ContactModel
{
...
public String HomePhone { get; set; }
public String MobilePhone { get; set; }
In the ContactController I have an action:
[HttpPost]
public ActionResult Index(Contact contact)
{
if (ModelState.IsValid)
{
contact.Store();
contact.SendEmail();
ViewData["ShowForm"] = false;
return View();
}
ViewData["ShowForm"] = true;
return View(contact);
}
When creating the view make sure to create a strongly typed view on the ContactModel
In the View I add the validation summary to display the error message if the requirement isn’t fulfilled.
<%= Html.ValidationSummary(true, "Please correct invalid and required fields.") %>
MinneBar Spring 2010
May 24, 2010
Today I attended MinneBar. MinneBar is an (un)conference aimed at getting those in Minnesota’s tech and design communities together to discuss topics that interest them. I try to go to as many conferences that I can. What I really like about this one is it isn’t just a presenter with an audience. At this conference it is all about everyone in the room adding input, the presenter is more of a facilitator of a discussion in the room.
All the sessions were under 5 main categories: Development, Design, Startups, Social Media and Other. Take a look at the schedule here.
Not only is this conference highly informational it also is a great opportunity to network. I met a lot of great people today and attended a lot of great sessions.
3 of my favorite sessions.
1. Success in Software Consulting by Scott K Davis.
This guy was a great speaker and had a lot of great advice for people looking to begin consulting and already consulting.
I was able to obtain a copy of his slides from his site.
2. Paper Prototypes: There and Back Again by John Malone, @john_malone.
He spoke about something I think everyone knows they should do, but few actually practice. Mocking, wireframing your site before you even get into designing it. He discussed 3 very simple ways to do this. Non of which require any artistic ability. The idea is actually to keep it light-weight so everyone can see how the site will be used.
- Use pencil and paper. This is something you can do while sitting on the couch.
- Use post-it notes. Using post-it notes allow you to move things around, ie. sign-up box, navigation tabs, etc.
- Use software to do it. In his example he suggested Balsamiq Mockups. I have also heard good things about this software. Many others were shouted out as well, the main thing is to just try one out and find what you like.
The group discussed ways that they convince their clients / bosses this is something we need to do. Some suggestions were:
- The prototypes are very easy to understand
- They’re not intimidating at all.
- They’re very easy to add input to
- Cheap! What does a pen and paper cost, $1.60?
- They will feel engaged, they get to add their input right away
- The 1/10/100 rule. If an issue is found in these, it’s only going to cost a buck to fix. If it is found in development it is only going to cost $10. If one is found in production it is going to cost $100.
** Update**
Slides from the session can now be found on slideshare.
3. How Can Minnesota Be Better? This was a panel discussion with 5 great panelists.
- Robert Weber – W3i
- Jon Dahl – Zencoder
- Marti Nyman – Altavail Partners
- Chris Smith – Coral Group
- Dan Grigsby
- Facilitated by Jeff Pesak & Mike Bollinger of Tech.mn
More information about the panelists can be found at TECH{dot}MN.
I thought the diversity of these 5 individuals were great and they really had a lot of good things to say. It seemed the dominance of the discussion was about startups getting funding which I was a little disappointed in. I really liked how Dan chimed in and basically said, “you know what you don’t have to have funding to start something.” They also compared the MN culture a lot to the Bay area and pointed out the many differences.
I took video of this session so watch it yourself. Let me know what you think in the comments. (The first video says Part II as the title,but it is Part I. If you have created a video before you know how long it takes, I didn’t feel it was worth it to redo it just the title).
Part I
MinneBar Spring 2010 Part I from Joel Dahlin on Vimeo.
Part II
MinneBar Spring 2010 Part II from Joel Dahlin on Vimeo.
Part III
MinneBar Spring 2010 Part III from Joel Dahlin on Vimeo.
Recap: The entire day was great. Not only did I learn a lot but I meat some amazing people and a few people that I have engaged with on twitter I was able to meet in real life which is always nice. This conference is such a great place to network. If you’re looking for a job, many companies are there recruiting. I will definitely be going to the next one.
Thanks to all the organizers and sponsors for putting on such a great event!
Create Excel file dynamically (Simple Way)
May 16, 2010
Scenerio: I’ve recently had a a few projects that I’ve created forms for. I have given the client a login to view all the form submissions, but in the end they want this data in an Excel file so they can easily manage it.
Research: I have found there a quite a few ways to achieve this. Some take advantage of the Excel interop, some create a .csv, some use third party tools, some use xml. Here is a good discussion I found on the topic at Stack Overflow, http://stackoverflow.com/questions/151005/create-excel-xls-and-xlsx-file-from-c.
All have pros and cons.
Solution: Here is what I have found to be the simplest way to read your dataset in an Excel file. First off, this doesn’t product a true Excel file, but it is something Excel can read into a table which often is all you need.
What I found is you can write the contents of a datagrid to an output stream that can be saved as a .xls file.
code snippet: I am using linq to bind to a datagrid
var registrations = from reg in db.Registrations
where reg.JumpPageId == int.Parse((String)e.CommandArgument)
orderby reg.TimeStamp descending
select reg;
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment; filename=registrants.xls");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = registrations;
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
LIke I said, this doesn’t output a true Excel file so when you go to open it, you will be prompted a warning:
It is saying the contents of the file are in a different format than what the .xls extension says it is.
Click Yes and it will open.
If you were to open this file in a text editor you will see that it really is just the datagrid html output.
Not the most elegant solution but it is a quick way to throw an Export to Excel button on a report page.
My next blog post will show how to create an Excel file using a third party tool.
Creating a dynamic container with a gradient
April 26, 2010
Here is the approach I take when creating containers that are dynamic in height.
First I start with a png image of the container.
I open this in Photoshop and create my slices (4 images) from the original image.
Image 2. The background that is repeated, only 1px high cut just below the header ![]()
Image 3. The bottom gradient of the container. The top is just below the section that is repeated and bottom just above the bottom slice where the corners begin to round. ![]()
Image 4. The bottom of the container.
Now for putting this together with xhtml and css.
Here is my xhtml:
<div class="container">
<h1>Container Demo</h1>
<div class="main">
<div class="bottom">
<p>Add your content here</p><p>Add your content here</p>
</div>
</div>
<img alt="" src="images/bottom.png" width="429" height="11" />
</div>
and my css:
body {background-color:#fff; margin:40px; font-size:62.5%; line-height:100%; font-family:Arial, Helvetica, Sans-Serif;}
.container{width:429px; background:transparent url(../images/header.png) no-repeat top left;}
.container h1{font-size:1.2em; font-weight:bold; line-height:2em; color:#fff; text-align:center; margin:0;}
.container .main{width:429px; background:transparent url(../images/background.png) repeat-y top left;}
.container img{display:block;}
.container .bottom{width:429px; background:transparent url(../images/gradient.png) no-repeat bottom left; padding:5px 15px;}
A little explanation of what is going on.
Basically it all comes together with the two layers. The bottom gradient is on top of the main layer. When content is added the bottom gradient layer pushes the parent main container down. We align the bottom gradient at the bottom of the cell with the rest of the background transparent so you see the main repeating background behind it.
Is this how others are doing this? Do you have a better approach that you can share?
-
Categories
- asp.net (11)
- Blog (1)
- Business (5)
- Conferences (1)
- Errors (3)
- Portfolio (2)
- Reviews (2)
- SQL Server (3)
- Tips (1)
- Uncategorized (1)
- Web Development (13)
-
Archives