Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

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>

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 { getset; }
   public string Role { getset; }
 
   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);    } }

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);

Monday, September 20, 2010

How to use a hidden input in MVC

While working on an e-commerce site, I needed to update my order total and submit it with the other form variables. My order total displayed to the user was just text, which doesn't get passed to the controller when submitted, so I needed a hidden input that I could update.

My html looks like this:

<p class="display_currency"><span id="totalprice">$0.00</span></p><%= Html.HiddenFor(m=>m.TotalOrder) %>

and my javascript. (snippet is from an UpdateTotal() function)

var total = 500.25
$("#totalprice").html("$" + total.toFixed(2));
$("#TotalOrder").val(total.toFixed(2)); //hidden control for model

when submitting the form, the model contains the correct value for TotalOrder

Saturday, September 18, 2010

How to create HTTP POST and GET methods with the same signature

When using Ajax Uploader (a very cool component) and MVC, I ran into a situation where I needed the same signature for the HTTP GET and HTTP POST controller actions. The compiler wouldn't let me use the same name. The ActionName attribute solved that problem.


[ActionName( "UploadArtwork" )]
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult UploadArtworkGet(string dataMyComponentUses)
{
...
return View( "UploadArtwork" );
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadArtwork(string dataMyComponentUses)
{
...
return View( "UploadArtwork" );
}

How to return a pdf file in MVC (instead of preview by browser)


public ActionResult GetPDF(string filename)
{
return File(filename, "application/pdf" , Server.HtmlEncode(filename));
}