Category: Controls

Oct 30 2009

Multiple Dropdownlist in Asp.net MVC

Create Database Purchase then create two tables in Purchase Database

Category table and Subcategory table

Goto Category and SubCategory tables

Steps to Create Multiple DropDownlist controls in Asp.net MVC

Start -> Programs -> choose VS2008 or 2005 -> File-> Project -> choose web (project type Visual C#) ->choose Asp.Net MVC Web Application -> Application name is myFirstMVCapp -> Go to Solution explorer -> you will observe Model, View and Controller folder.

First Create Linq to Sql classes

In Model , create interface name is Categories.cs

using myFirstMVCapp.Models;

namespace myFirstMVCapp.Models

{

public interface ICategories

{

IQueryable<tblCategory> GetCategories();

IQueryable<tblSubCategory> GetSubCategories();

IQueryable<tblSubCategory> GetSubCategoriesByID(int catid);

}

public class Categories:ICategories

{

PurchaseDataContext db = new PurchaseDataContext();

public IQueryable<tblCategory> GetCategories()

{

return db.tblCategories;

}

public IQueryable<tblSubCategory> GetSubCategories()

{

return db.tblSubCategories;

}

public IQueryable<tblSubCategory> GetSubCategoriesByID(int catid)

{

return from subcategory in GetSubCategories()

where subcategory.CategoryID == catid

select subcategory;

}

}

}

In Controller, Create CategoriesController

using myFirstMVCapp.Models;

namespace myFirstMVCapp.Controllers

{

public class CategoriesController : Controller

{

//

// GET: /Categories/

PurchaseDataContext db = new PurchaseDataContext();

#region “Repository”

ICategories categoriesRepository;

ISubCategories subCategoriesRepository;

public CategoriesController() :

this(new Categories())

{

}

public CategoriesController(ICategories repository)

{

categoriesRepository = repository;

}

#endregion

public ActionResult Index()

{

ViewData["Categories"] = new SelectList

(

db.tblCategories,

CategoryID“,

CategoryName

);

return View();

}

#region “JSonResult”

public JsonResult FindSubCategoriesByCatID(int catID)

{

// Simulate Loading Data “wait”

System.Threading.Thread.Sleep(500);

// return Json result using LINQ to SQL

return new JsonResult

{

Data = categoriesRepository.GetSubCategoriesByID(catID)

};

}

#endregion

}

}

In Site.Master add below lines inside head tags

<head>

<script src=”../../Scripts/jquery-1.3.2.min.js” type=”text/javascript”></script>

<asp:ContentPlaceHolder ID=”HeadContent” runat=”server” />

</head>

Design page coding in Categories folder index page

<%@ Page Title=”" Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage<myFirstMVCapp.Models.PurchaseDataContext>” %>

<asp:Content ID=”Content1″ ContentPlaceHolderID=”TitleContent” runat=”server”>

Index

</asp:Content>

<asp:Content ID=”Head” ContentPlaceHolderID=”HeadContent” runat=”server”>

<script type=”text/javascript”>

$(document).ready(function() {

$(”select#Categories“).change(function() {

var color = $(”#Categories > option:selected“).attr(”value”);

$.ajax({

type: “GET”,

contentType: “application/json; charset=utf-8″,

url: “FindSubCategory/” + color,

data: “{}”,

dataType: “json”,

success: function(data) {

$(’#SubCategoryDiv > div’).remove(); // remove any existing SubCategory

if (data.length > 0) {

var options = ”;

for (p in data) {

var product = data[p];

options += “<option value=’” + product.SubCategoryID + “‘>” + product.SubCategory + “</option>”;

}

$(”#SubCategory“).removeAttr(’disabled’).html(options);

} else {

$(”#SubCategory“).attr(’disabled’, true).html(”);

$(”#SubCategoryDiv”).append(’<div>(None Found)</div>’);

}

}

});

});

});

</script>

</asp:Content>

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>

<h2>Index</h2>

<p>

<label for=”Categories“>Categories:</label>

<%=Html.DropDownList(”Categories“)%>

</p>

<p>

<div id=”SubCategoryDiv”></div>

</p>

<p>

<label for=”SubCategory”>SubCategory:</label>

<select id=”SubCategory” disabled></select>

</p>

</asp:Content>

In Global.asax file

routes.MapRoute(

FindSubCategory“,

FindSubCategory/{catID}”,

new { controller = “Categories”, action = “FindSubCategoriesByCatID“, catID = “” }

);

FindSubCategory is from JSon Script

Url: FindSubCategory

In Global.asax: FindSubCategory

FindSubCategoriesByCatID is from CategoriesController Json Function

#region “JSonResult”

public JsonResult FindSubCategoriesByCatID(int catID)

{

// Simulate Loading Data “wait”

System.Threading.Thread.Sleep(500);

// return Json result using LINQ to SQL

return new JsonResult

{

Data = categoriesRepository.GetSubCategoriesByID(catID)

};

}

#endregion

Oct 29 2009

How to Upload Files in Asp.net MVC

FileUpload Control

Model folder contains:  Purchase.dbml, IMediaRepository.cs Interface and MediaRepository.cs class file

Controller: Create New controller MediaController

View: Create New Folder name is Media

if controller name MediaController

view folder name is Media (see the below figure round controller and view folder name )

Note: Create Folder in Project SolutionExplorer name is Uploads

mvc-fileupload

mvc-fileupload

IMediaRepository.cs

public interface IMediaRepository

{

void Add(Media media);

void Save();

}

MediaRepository

public class MediaRepository :IMediaRepository

{

PurchaseDataContext db = new PurchaseDataContext();

public void Add(Media media)

{

db.Medias.InsertOnSubmit(media);

}

public void Save()

{

db.SubmitChanges();

}

}

MediaController

public string filename;

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Create(Media media)

{

try

{

// TempData["Id"] = Request.Form["Id"];

// TODO: Add insert logic here

foreach (string inputTagName in Request.Files)

{

HttpPostedFileBase file = Request.Files[inputTagName];

if (file.ContentLength > 0)

{

string filePath = Path.Combine(HttpContext.Server.MapPath(”../Uploads“)

, Path.GetFileName(file.FileName));

file.SaveAs(filePath);

filename  = file.FileName;

}

}

//TempData["FileName"] = media.FileName;

media.FileName = filename;  //to get filename Remmber

mediaRepository.Add(media);

mediaRepository.Save();

return RedirectToAction(”Index”);

}

catch

{

return View();

}

}

View Folder

Create.aspx (Media/Create.aspx)

Remmeber this line

<% using (Html.BeginForm(”Create”, “Media”, FormMethod.Post, new { enctype = “multipart/form-data” }))

{%>

—————————————————————

asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>

<h2>Create</h2>

<%= Html.ValidationSummary(”Create was unsuccessful. Please correct the errors and try again.”) %>

<%–  <form action=”/Media/Create” method=”post”>–%>

<%– <% using (Html.BeginForm()) {%>–%>

<% using (Html.BeginForm(”Create“, “Media“, FormMethod.Post, new { enctype = “multipart/form-data” }))

{%>

<fieldset>

<legend>Fields</legend>

<p>

<label for=”Id”>Id:</label>

<%= Html.TextBox(”Id“) %>

<%= Html.ValidationMessage(”Id”, “*”) %>

</p>

<p>

<label for=”FileName”>FileName:</label>

<input type=”file“  name=”FileName” size=”23″/>

</p>

<p>

<label for=”Title”>Title:</label>

<%= Html.TextBox(”Title“) %>

<%= Html.ValidationMessage(”Title”, “*”) %>

</p>

<p>

<label for=”Description”>Description:</label>

<%= Html.TextBox(”Description“) %>

<%= Html.ValidationMessage(”Description”, “*”) %>

</p>

<p>

<label for=”EntryDate”>EntryDate:</label>

<%= Html.TextBox(”EntryDate“) %>

<%= Html.ValidationMessage(”EntryDate”, “*”) %>

</p>

<p>

<input type=”submit” value=”Create” />

</p>

</fieldset>

<% } %>

<div>

<%=Html.ActionLink(”Back to List”, “Index”) %>

</div>

<%–</form>–%>

</asp:Content>

Alibi3col theme by Themocracy