Sorted By: Tag (code-review)

ASP.NET MVC Code Review #2 - A Way of Working with Html Select Element (AKA DropDownList) In ASP.NET MVC

This is the #2 of the series of blog posts which is about some core scenarios on ASP.NET MVC: A Way of Working with Html Select Element (AKA DropDownList) In ASP.NET MVC
2011-12-30 14:28
Tugberk Ugurlu


This is the #2 of the series of blog posts which is about some core scenarios on ASP.NET MVC. In this one, code review #2, I will try to show you the best way of working with Html Select element (AKA DropDownList) in ASP.NET MVC. Here is the code:

Repository Class which generates the dummy data for the demo:

public class ProductCategory {

    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
}

public class ProductCategoryRepo {

    public List<ProductCategory> GetAll() {

        List<ProductCategory> categories = new List<ProductCategory>();

        for (int i = 1; i <= 10; i++) {

            categories.Add(new ProductCategory { 
                CategoryId = i,
                CategoryName = string.Format("Category {0}", i)
            });
        }

        return categories;
    }
}

Controller:

public class SampleController : Controller {

    private readonly ProductCategoryRepo productCategoryRepo = 
         new ProductCategoryRepo();

    public ActionResult Index() {

        registerProductCategorySelectListViewBag();
        return View();
    }

    private void registerProductCategorySelectListViewBag() {

        ViewBag.ProductCategorySelectList = 
            productCategoryRepo.GetAll().Select(
                c => new SelectListItem { 
                    Text = c.CategoryName,
                    Value = c.CategoryId.ToString()
                }
            );
    }
}

View:

@{
    ViewBag.Title = "HTML Select List Sample";
}

<h2>HTML Select List Sample</h2>

<p>
    <strong>Product Categories:</strong>
</p>
<p>
    @Html.DropDownList(
        "ProductCategoryId", 
        (IEnumerable<SelectListItem>)ViewBag.ProductCategorySelectList
    )
</p>

Let’s see what it generates for us:

Output HTML of Select element:

<select id="ProductCategoryId" name="ProductCategoryId">
    <option value="1">Category 1</option>
    <option value="2">Category 2</option>
    <option value="3">Category 3</option>
    <option value="4">Category 4</option>
    <option value="5">Category 5</option>
    <option value="6">Category 6</option>
    <option value="7">Category 7</option>
    <option value="8">Category 8</option>
    <option value="9">Category 9</option>
    <option value="10">Category 10</option>
</select>

Just like what I expected. On the controller, you see that I newed up SelectListItem classes and pass them to the view through the ViewDataDictionary. SelectListItem class works nicely with DropDownList and DropDownListFor Html helpers within ASP.NET MVC as you see inside the view code above.

So, don’t try to reinvent the wheel and don’t get into for and foreach loops in order just to create a select element. SelectListItem has been put inside the library just for this purpose and leverage it.

ASP.NET MVC Code Review #1 - File Upload With HttpPostedFileBase Class

This is #1 of the series of blog posts which is about some core scenarios on ASP.NET MVC: File Upload With HttpPostedFileBase Class
2011-12-29 21:25
Tugberk Ugurlu


Today, I decided to change my blogging style a little bit. I always try to write posts which contains detailed information about the subject but I realized that it prevents me from writing much more useful things. So, from now on, I will drop a bunch of code on the screen and talk about that briefly.

This is the beginning of the series of blog posts which is about some core scenarios on ASP.NET MVC. In this one, code review #1, I will give you an example on how to get file upload functionality working in ASP.NET MVC. Here is the code:

Controller:

public class SampleController : Controller {

    public ActionResult Index() {
        return View();
    }

    [ActionName("Index")]
    [ValidateAntiForgeryToken, HttpPost]
    public ActionResult Index_post(HttpPostedFileBase File) {

        //Check if the file is not null and content length is bigger than 0
        if (File != null && File.ContentLength > 0) {

            //Check if folder is there
            if(!System.IO.Directory.Exists(Server.MapPath("~/Content/PostedFiles")))
                System.IO.Directory.CreateDirectory(
                    Server.MapPath("~/Content/PostedFiles")
                );

            //Set the full path
            string path = System.IO.Path.Combine(
                Server.MapPath("~/Content/PostedFiles"),
                System.IO.Path.GetFileName(File.FileName)
            );

            //Save the thing
            File.SaveAs(path);

            TempData["Result"] = "File created successfully!";
        }

        //RedirectToAction so that we can get rid of so-called "Form Resubmission"
        return RedirectToAction("Index");
    }

}

View:

@{
    ViewBag.Title = "File Upload Sample";
}
<h2>File Upload Sample</h2>

@if (TempData["Result"] != null) { 
    <ul>
        <li>@TempData["Result"]</li>
    </ul>
}

@using (Html.BeginForm("index", "sample", 
    FormMethod.Post, new { enctype = "multipart/form-data" })) {
 
    @Html.AntiForgeryToken()
    
    <input type="file" name="File" />
    <p>
        <input type="submit" value="Upload" />
    </p>
}

Actually, code explains itself nicely here but I see one thing to worth pointing out here. HttpPostedFileBaseModelBinder class from System.Web.Mvc namespace is the class which binds a model to a posted file. So, the parameter (which is type of HttpPostedFileBase) of the Index_post method receives the posted file.

Pretty neat stuff. Hope you enjoy it.

Tags