Tuesday, April 5, 2016

Upload File In MVC

Add the file tag in the view.

@using(Html.BeginForm("SaveFile", "Employee", null, FormMethod.Post, new { enctype="multipart/form-data" }))
{
<input type="file" name="file" required />
<input type="submit" value="Submit" />
}

EmployeeController

[HttpPost]
public class SaveFile()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Employee/Images/"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index", "Employee");
}

DropDownList In MVC

This post will explain you the different ways of binding the dropdownlist in ASP.NET MVC razor view engine.

Bind DropDownList with the static values.


@Html.DropDownList("Role", new List<SelectListItem>(){new SelectListItem(){ Text= "Admin", Value = "1"},new SelectListItem(){ Text= "Guest", Value = "2"},}, "Please Select", new { @class = "form-control" })

Bind DropDownList with ViewData/ViewBag values.

In controller index method the List<SelectListItem> are added and assigned to ViewBag.
public ActionResult Index()
{
List<SelectListItem> roles = new List<SelectListItem>();
roles.Add(new SelectListItem { Text = "Admin", Value = "1" });
roles.Add(new SelectListItem { Text = "Guest", Value = "2" });
ViewBag.Role = roles;
return View();
}
You can render the dropdownlist as below. Dropdownlist helper will have many overloading methods with different parameters.
@Html.DropDownList("Role", null, "All", new { @class = "control-label" })
OR
@Html.DropDownList("Role")