Blog
Setting GroupName of RadioButton in ListView
December 5, 2010 Author: Joel
Problem: It seems there is a bug in asp.net where if you add a radio button to a control such as a ListView, Repeater, etc, the GroupName will not be the same for every RadioButton because of the asp.net naming convention adding the control hierarchy to the name.
For example I have a ListView that I include a RadioButton with the ID of “rbMorning”. 3 ListItems are dynamically created with a rendered output name of:
name="ctl00$cphMain$lvMorningSessions$ctrl0$rbMorning"
name="ctl00$cphMain$lvMorningSessions$ctrl1$rbMorning"
and
name="ctl00$cphMain$lvMorningSessions$ctrl2$rbMorning"
In this case a user would be allowed to select all 3 RadioButtons, defeating the purpose of using a RadioButton control.
Solution: Update the names with jQuery. You will notice that that each name ends with the id of the RadioButton that you set in the ListView. So I basically search for that and update the name to a name that all radio buttons will share.
Just a few lines of code to do this. It all is included right here. I am assuming you need to add jQuery to the page here as well.
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('input[name$="rbMorning"]').attr('name', 'rbMorning');
});
</script>
That’s it. I hope this helps someone. I am really surprised this is still an issue in asp.net 4.0 even.
Could not load file or assembly ‘AjaxControlToolkit’ or one of its dependencies.
November 6, 2010 Author: Joel
This is the second time I’ve encountered this exception so I need to blog this in case I run into it again. I had to search for the solution this time around again. It occurred after my pc crashed.
Could not load file or assembly ‘AjaxControlToolkit’ or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0×80070057 (E_INVALIDARG))
Solution:
Clear out the temporary framework files for your project in:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\
Windows 7 users:
C:\Users\[username]\AppData\Local\Temp\Temporary ASP.NET Files\
For 64 bit systems with ‘Framework’ in the path the full path is:
C:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\
All credit for this solution goes to SolutionCottage.com, http://www.solutioncottage.com/ShowSolution.aspx?solID=59
Add css class attribute to html helpers in asp.NET MVC 2
August 26, 2010 Author: Joel
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 Author: Joel
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.") %>
Create Excel file dynamically (Simple Way)
May 16, 2010 Author: Joel
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.
-
Categories
- asp.net (13)
- Blog (3)
- Business (6)
- Conferences (1)
- Errors (7)
- Office (1)
- Portfolio (3)
- Reviews (3)
- SEO (4)
- SQL Server (4)
- Tips (2)
- Uncategorized (3)
- Web Development (18)
-
Archives
- October 2012
- August 2012
- July 2012
- June 2012
- May 2012
- April 2012
- January 2012
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- April 2009
- March 2009