Tuesday, August 16, 2011

How to use a collection in MVC which will populate the ViewModel correctly


The view model below is a collection of strings called Images


public class PostItemViewModel
{
   public PostItemViewModel()
   {
      Images = new List<string>();
   }

   public List<string> Images { get; set; }
}


The View would look something like the code below.  The reason for the HiddenFor, is so that when  you post back to your controller, the view model that is posted back will contain the Image list.


<table>
   <tr>
   <%
   for (int i = 0; i < Model.Images.Count; i++)
   {
   %>
      <td>
         <%= Html.HiddenFor(m => m.Images[i]) %>
         <img alt="<%= Model.Images[i] %>" width="50" src="\Uploads\<%= Model.Images[i] %>" />
      </td>
   </tr>
</table>

Tuesday, April 12, 2011

How to show differences in two files using tortoise SVN

Right click on the file > Tortoise SVN > Show log

Click on the first version of the file

[Ctrl] Click on the second file

Right click > Compare Revisions

Thursday, March 17, 2011

How to use multiple login pages in MVC

When you only have one login page, then it's easy to add the authorize attribute to your action and you'll automatically be directed to the login page in your web.config


[Authorize(Roles = "Administrator")]
public ActionResult EditCategory(int id)
{
   return View();
}
On my sites, I have a separate login page for the Administrative area, so I needed to create a custom attribute.

[CustomAuthorization(LoginPage = "~/Admin/LogOn", Role = "Administrator")]
public ActionResult EditCategory(int id)
{
   return View();
}
/// <summary>
/// Allows you to specify the Login Page and Role with an attribute:  [CustomAuthorization(LoginPage="~/Admin/LogOn",Role="Administrator")]
/// </summary>
/// <param name="filterContext"></param>
public class CustomAuthorization : AuthorizeAttribute
{
   public string LoginPage { get; set; }
   public string Role { get; set; }
 
   public override void OnAuthorization(AuthorizationContext filterContext)
   {
      //Send the return url to the login page
      LoginPage += "?ReturnUrl=" + filterContext.HttpContext.Request.RawUrl;
      if (!filterContext.HttpContext.User.Identity.IsAuthenticated)       {          filterContext.HttpContext.Response.Redirect(LoginPage);       }       else       {          if (Role != null)          {             if(!filterContext.HttpContext.User.IsInRole(Role))                filterContext.HttpContext.Response.Redirect(LoginPage);          }       }       base.OnAuthorization(filterContext);    } }

Wednesday, March 9, 2011

How to calculate age in Excel

This formula will calculate a person's age in excel (assuming date of birth is in cell A1)


=IF(MONTH(TODAY())>MONTH(A1),YEAR(TODAY())-YEAR(A1),
 IF(AND(MONTH(TODAY())=MONTH(A1),DAY(TODAY())>=DAY(A1)),
 YEAR(TODAY())-YEAR(A1),(YEAR(TODAY())-YEAR(A1))-1))

Thursday, February 24, 2011

How to change the title of a jquery dialog

Here is an image that a user can click to get help

   <img src="/Content/images/Help.png" style="cursor:pointer" onclick="javascript:ShowHelp('My Title')" />

Here is the jquery dialog

   <div id="dialog-help" title="" style="background:white">
      <div id="divHelpContents"></div>
   </div>

Javascript function to set up the dialog

      $(document).ready(function ()
      {
         //Help popup
         $("#dialog-help").dialog({ autoOpen: false
            , modal: true
            , width: 415
            , height: 300
            , show: "blind" //animation effect
            , hide: "clip" //animation effect            
            , draggable: true
            , resizable: false
            , buttons: {
               Ok: function ()
               {
                  $(this).dialog("close");
               }
            }
         });
      });
Here is a function that will update the title, help contents, and open the dialog
      function ShowHelp(topic)
      {
            $("#dialog-help").dialog('option', 'title', topic);
            $("#divHelpContents").html("Show some help contents here");
            $("#dialog-help").dialog("open");
      }

Friday, February 18, 2011

How to get paste to work with Remote Desktop Connection

You can copy things to the clipboard and paste them into your remote desktop connection.

What do you do when paste stops working ?

1.  Close your remote desktop connection (you don't need to log out).

2.  Reconnect.

How to re-insert deleted records when there is an identity field

My customers like to delete important records and then have me restore them from a backup when they realize their mistake.

When the column has an identity field, and you want to restore the records with the same number as they had before deleted, you must turn on identity insert with this TSql command

SET IDENTITY_INSERT {YourTableName} ON 

insert the deleted records

SET IDENTITY_INSERT {YourTableName} OFF 

Friday, January 28, 2011

How to detect if an element is hidden in jQuery

This will work when myID was hidden using .hide( ) and displayed using .show( )


if($("#myID").is(":visible"))
   $("#myID").hide();
else
   $("#myID").show();

How to get rid of Unexpected error 0x8ffe2740 occurred in IIS 5

Running XP, I stopped my Default website and rebooted my computer.

Then when I tried to restart my website, I was getting the error "Unexpected error 0x8ffe2740 occurred".

This was because Skype started before IIS.

To resolve, quite Skype, restart IIS, start your site, then restart Skype

Thursday, January 27, 2011

How to refresh Intellisense in SQL Server 2008

Intellisense in SQL Server 2008 Management Studio is a great feature. When adding a table, column etc, your Intellisense doesn't know about the change right away.

To fix this

Edit > Intellisense > Refresh Local Cache

Thursday, January 20, 2011

How to find the value of a dropdown in a user control using jQuery

you may have an asp:Dropdown control with an id="ddViewBy" like below.

<asp:DropDownList class="ddList" runat="server" ID="ddViewBy" AutoPostBack="true" OnSelectedIndexChanged="ddViewBy_Changed"><asp:DropDownList>

If your dropdownlist is in a user control and the usercontrol is in a content place holder, then when you view source, on the web page the id of the control would change to something like this:

id="ctl00_phContent_ucSearchFilter_ddViewBy"

To find the value of the dropdown using jQuery, use the following selector

$('select[id$=ddViewBy]').val();

This is reliable, because your user control could be in different place holders which would cause the first part of the id to be different. The controls id will always end with your original name.

The $= means "ends with"

Just an FYI, ^= means "begins with"


Wednesday, January 19, 2011

How to create the ASP.Net membership tables

Sometimes web hosts (such as godaddy) will set up the aspnet membership tables for you in your database as part of the setup.

When you need to set them up locally, use the following .Net framework command
//For servername you can use "(local)" if the database is a local SQL Server install
System.Web.Management.SqlServices.Install(txtServer.Text, txtUserName.Text, txtPassword.Text, txtDatabase.Text, SqlFeatures.All);

Monday, November 29, 2010

How to strip non-alphanumeric chars from a string

The example below also leaves the space character and commas intact.

      private string StripSpecialChars(string inputString)
{
return (Regex.Replace(StripHTML(inputString), "[^A-Za-z0-9 ,]", ""));
}

How to strip HTML tags out of a string

      static string StripHTML(string inputString)
{
return Regex.Replace
(inputString, "<.*?>", string.Empty);
}

Saturday, November 13, 2010

How to reseed an identity field

When I create e-commerce sites, the order numbers always start at 1. My customers like to pretend that they've had lots of orders when they launch, so I need to update their order number to something higher. The problem is this is always the identity field of the table. This command does the trick. It doesn't update the old order numbers, but I don't need those updated so it's no big deal.

DBCC CHECKIDENT('order', RESEED, 1000070 )

Tuesday, October 19, 2010

How to set the selected item in an MVC Dropdownlist

The first parameter to the Html.DropDownList needs to be a name that does not match the name in your model. Below I used "OptionId" instead of "Options".

View

<%= Html.DropDownList("OptionId",Model.Options) %>

Controller

SelectListItem item1 = new SelectListItem();

item1.Text = "Red";

item1.Value = "Red";

item1.Selected = false;

viewModel.Options.Add(item1);

SelectListItem item2 = new SelectListItem();

item2.Text = "Green";

item2.Value = "Green";

item2.Selected = true;

viewModel.Options.Add(item2);

SelectListItem item3 = new SelectListItem();

item3.Text = "Blue";

item3.Value = "Blue";

item3.Selected = false;

viewModel.Options.Add(item3);

Tuesday, October 5, 2010

How to create a modal dialog in jQuery and prevent scrolling in background


$(document).ready(function() {

$("#dialog").dialog({ autoOpen: false

, modal: true

, buttons:

{

"Cancel": function() {

$(this).dialog("close");

$("body").css("overflow", "auto"); }

, "Save": function() {

$(this).dialog("close");

$("body").css("overflow", "auto"); }

}

});

});


function RenameFile(filename, id) {

$("#OldFilename").html("From: " + filename);

$("#NewFilename").val(filename);

$("#dialog").dialog("open");

$("body").css("overflow", "hidden");

}


<div id="dialog" title="Change Filename">

<p id="OldFilename"><b>From: </b>oldfilename.doc</p>

<p><b>To: </b>

<input id="NewFilename" type="text" style="width:200px" /></p>

</div>


<a style="cursor:hand;text-decoration:underline;color:Blue" onclick="javascript:RenameFile('<%= Html.Encode(doc.FileName) %>',<%= doc.PathID %>)">rename</a>



Wednesday, September 29, 2010

How to resolve unresolved type System.Web.Security.MembershipCreateStatus which appears after converting from vs2008 to vs2010

I upgraded a project I was working on from vs2008 to vs2010 and started getting an error for an unresolved type: System.Web.Security.MembershipCreateStatus.

My project was targeting the .NET Framework 3.5 and during the conversion, I selected not to change the target to the .NET Framework 4.0.

This issue was occurring in my Test project which was generated automatically when I created an MVC 2 project in vs2008. In vs2010, test projects cannot target the 3.5 Framework (by design). The quick fix was to delete AccountController.cs in the test project.

A better solution would be create another MVC2 project in vs2010 and use the generated Test project.

Thursday, September 23, 2010

How to add a configuration file to your class library

I have a web project with some configuration settings in the web.config. I added a class library to the project and realized I could not access those values from the class library. The solution is to add an app.config file to the class library project and copy the configuration settings from the web.config to the app.config.

To access ConfigurationManager from the class library, I need to add a reference to the System.Configuration .Net assembly.

If you don't like having the settings in both places, you could retrieve the configuration values for the web application by using the class library (app.config), and remove the configuration values from the web.config.