binding dropdownlist by another dropdownlist in mvc 3 - asp.net-mvc-3

I'm new with mvc and I have 2 dropdownlists and I need to bind second one by first one using mvc 3..
Code sample
#<table>
<tr>
<td>
#Html.DropDownList("Brands", Model.Brands, "Select Brand", New With {.style = "width:150px;"})
</td>
</tr>
<tr>
<td>
#Html.DropDownList("Models", Model.Models, "Select Model", New With {.style = "width:150px;"})
</td>
</tr>
<tr>
<td>
#Html.DropDownList("Devices", Model.Devices, "Select Device", New With {.style = "width:150px;"})
</td>
</tr>
<tr>
<td>
#Html.DropDownList("Systems", Model.Systems, "Select System", New With {.style = "width:150px;"})
</td>
</tr>
</table>
I need to fill Models by Brands and Fill Devices by Models.
any help please..
Thanks

In view:
#Html.DropDownListFor( x => x.Model, new SelectList( LookupUtils.GetModelsList(Model.Brand), "Value", "Text", Model.Model))
LookupUtils is a static class have:
public static List<SelectListItem> GetModelsList(int brand)
{
var dataContext = new YourDataContext( );
var data = dataContext.GetModelsFn(brand).ToList();
var result = ( from res in data
select new SelectListItem()
{
Text = res.modelName,
Value = res.modelId.ToString()
} ).ToList();
return result;
}
For dynamicly update some dropdown lists, you should use jQuery-Collapse plugin: http://github.com/danielstocks/jQuery-Collapse/

Related

AJAX call to delete DB record

I have a page that displays a list of courses for an individual. The page allows a user to delete a course from the selected users course list. When the delete button is clicked, that course should be deleted from the course list and the list of courses should be re-displayed. In my controller I was trying to delete the record, then call the listCourses view (view that initially lists the courses for a user) but when I click the delete button, nothing happens. Below is my code:
View to select a student:
#foreach (var stu in Model)
{
<tr>
<td class="stulisttd">
#stu.Id
</td>
<td class="stulisttd">
#stu.fname
</td>
<td class="stulisttd">
#stu.lname
</td>
<td class="thEditButton">
#using (Ajax.BeginForm("addCourses", "ManageStudentCourses", stuEditCourses))
{
#Html.TextBox("stuId", (string)stu.Id, new { #class = "listCourseText" })
<input type="submit" id="addCourses" name="addCourses" value='Add Courses' class="AllTracksButtons" />
}
</td>
<td class="thEditButton">
#using (Ajax.BeginForm("listCourses", "ManageStudentCourses", stuEditCourses))
{
#Html.TextBox("stuId", (string)stu.Id, new { #class = "listCourseText" })
<input type="submit" value="List Courses" class="AllTracksButtons" id=#stu.Id />
}
</td>
</tr>
}
View that lists the courses for user selected:
#foreach (var course in Model)
{
using (Ajax.BeginForm("deleteCourses", "ManageStudentCourses", stuListEditCourses))
{
<tr class="trCourseList">
<td>
#course.courseAbNum
#Html.TextBox("courseAbNum", (string)course.courseAbNum, new { #class = "editCourseText" })
</td>
<td>
#course.courseDesc
</td>
<td>
#course.status
</td>
<td>
#course.grade
</td>
<td>
#course.credits
</td>
<td>
<input type="submit" value="Delete" class="courseListButtons" id="displayEdit" />
</td>
</tr>
}
deleteCourses controller:
public PartialViewResult deleteCourses(string courseAbNum)
{
KuPlanEntities db = new KuPlanEntities();
var deleteCourse = (from course in db.COURSE_TAKEN
where course.courseAbNum == courseAbNum && course.Id == "000160228"
select course);
foreach (var course in deleteCourse)
{
db.COURSE_TAKEN.Remove(course);
db.SaveChanges();
}
var stuCourses = (from studCourse in db.COURSE_TAKEN
join course in db.COURSEs on studCourse.courseAbNum equals course.courseAbNum
where studCourse.Id == "000160228"
select new courseListViewModel { id = studCourse.Id, courseAbNum = studCourse.courseAbNum, status = studCourse.status, grade = studCourse.grade, courseDesc = course.courseDesc, credits = course.credits });
return PartialView("~/Views/ManageStudentCourses/listCourses.cshtml", stuCourses);
}
I think you're going to have an issue with this code
foreach (var course in deleteCourse)
{
db.COURSE_TAKEN.Remove(course);
db.SaveChanges();
}
You'll likely get the error "Collection was modified; enumeration operation may not execute."
To get around this you can use this hack
while (db.COURSE_TAKEN.Where(x => x.ID == ID).Count() != 0)
{
COURSE_TAKEN course = db.COURSE_TAKEN.Where(x => x.ID == ID).FirstOrDefault();
db.COURSE_TAKEN.Remove(course);
db.SaveChanges();
}
Hope this helps.

how to dynamically edit the bind data in sql using mvc3 web grid

i am new to mvc.. i have a task that, i have to bind data from existing table in sql using asp.net mvc3(Razor) Web Grid .. now i have to edit the data in webGrid.. i dont know how the edit operation is going to made... Plzz Help me out...
i have given my bind data.. plz let me know how to edit it...
Controller:
public ActionResult Index()
{
var list = GetList();
return View(list);
}
public List<Teacher> GetList()
{
var modelList = new List<Teacher>();
using (SqlConnection conn = new SqlConnection(#"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Demo;Data Source=CIPL41\SQLEXPRESS"))
{
conn.Open();
SqlCommand dCmd = new SqlCommand("Select T_Id,T_Name,T_Address,Sub_Id from teacher", conn);
SqlDataAdapter da = new SqlDataAdapter(dCmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var model = new Teacher();
model.T_Id = Convert.ToInt32(ds.Tables[0].Rows[i]["T_Id"]);
model.T_Name = ds.Tables[0].Rows[i]["T_Name"].ToString();
model.T_Address = ds.Tables[0].Rows[i]["T_Address"].ToString();
model.Sub_Id = ds.Tables[0].Rows[i]["Sub_Id"].ToString();
modelList.Add(model);
}
}
return modelList;
}
//
Index.cshtml
#model IEnumerable<MvcApplication1.Models.Teacher>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm("Index", "Teacher"))
{
<table>
<tr>
<th></th>
<th>
T_Id
</th>
<th>
T_Name
</th>
<th>
T_Address
</th>
<th>
Sub_Id
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.T_Id }) |
#* #Html.ActionLink("Details", "Details", new { id=item.T_Id }) |*#
#Html.ActionLink("Delete", "Delete", new { id=item.T_Id })
</td>
<td>
#Html.TextBox("T_Id", item.T_Id , new { #style = "width:100px;" })
</td>
<td>
#Html.TextBox("T_Name", item.T_Name , new { #style = "width:100px;" })
</td>
<td>
#Html.TextBox("T_Address", item.T_Address , new { #style = "width:100px;" })
</td>
<td>
#Html.TextBox("Sub_Id",item.Sub_Id,new { #style = "width:100px;"})
</td>
</tr>
}
</table>
Plz help me out....
Have a look at this tutorial http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/examining-the-edit-methods-and-edit-view
I think it explains exactly what you're trying to do.

How to bind data to Grid in MVC3?

For past few days I had been working with MVC...
I have to show a bunch of data in a grid...these all days I managed to show it in a table but my requirement is to bind it to jquery grid or Webgrid...
I am stuck with this I don't know how to do this expecting ideas and suggestions....
Controller
public ActionResult Index()
{
var bugList = GetList();
return View(bugList);
}
public List<ProjectModel> GetList()
{
var modelList = new List<ProjectModel>();
using (SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True"))
{
conn.Open();
SqlCommand dCmd = new SqlCommand("Select * from Projects", conn);
SqlDataAdapter da = new SqlDataAdapter(dCmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var model = new ProjectModel();
model.ID = Convert.ToInt16(ds.Tables[0].Rows[i]["ProjectID"]);
model.projectName = ds.Tables[0].Rows[i]["projectName"].ToString();
model.Description = ds.Tables[0].Rows[i]["Description"].ToString();
model.status = ds.Tables[0].Rows[i]["Status"].ToString();
modelList.Add(model);
}
}
return modelList;
}
View (ASPX)
<table>
<thead align="center">
<tr class="BoldCenterAlignHeaderStyle">
<th>
ProjectName
</th>
<th>
Status
</th>
<th align="center">
Edit
</th>
</tr>
</thead>
<% foreach (var item in Model) { %>
<tr>
<td>
<%:Html.LabelForModel(item.projectName) %>
</td>
<td>
<%:Html.LabelForModel(item.status) %>
</td>
<td align="center">
<img src="../../Content/edit.gif" height="8px"/>
<%--<%:Html.ActionLink("Edit", "Edit", new { id = item.ID })%> --%>
<%-- <img src="../../Content/delete.gif" height="8px" />--%>
</td>
</tr>
<%} %>
if i can do paging in a table how can i do that or else how should i display he data in a grid can any one help me please....can any one explain me how to do this
Example for webgrid:
#model IEnumerable<ProjectModel>
#{
var grid = new WebGrid(
source: Model,
rowsPerPage: 4);
}
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "header",
rowStyle: "row",
footerStyle: "footer",
alternatingRowStyle: "altRow",
columns: grid.Columns (
grid.Column("projectName"),
grid.Column("ProjectID")
))
You can use Webgrid for this.
Here are few links for understanding how webgrid works
Introduction to webgrid
http://www.mikesdotnetting.com/Article/154/Looking-At-The-WebMatrix-WebGrid
http://msdn.microsoft.com/en-us/magazine/hh288075.aspx
Paging in webgrid
http://yassershaikh.com/webgrid-paging-with-pager-method-in-razor-mvc/
Advanced (Efficient) Paging in Webgrid
http://www.dotnetcurry.com/ShowArticle.aspx?ID=615
Hope this helps..!

mvccontrib grid - How to add <tr> id

I want to add an id to the "tr" elements of the mvccontrib grid I build:
<tr id="0"/>
<tr id="1"/>
so if the table contains 10 rows, the ids are 0 through to 9.
One way is to add an additional item to my entity to store this value and then create this as a hidden column with the id as the value of this item - not very elegant.
Is there a more elegant way to do this?
Thanks
I've got this far but now it complains at the RenderUsing line, any ideas?
#model IEnumerable<Tens.Models.UserPreviousNamesView>
<div class="demo_jui">
#{
var userId = 0;
foreach (var item in Model)
{
userId = item.Id;
break;
}
#(Html.Grid(Model.Select((item,index) => new { Item = item, Index = index}))
.Columns(col =>
{
col.For(p => p.Item.Title);
col.For(p => p.Item.Name);
col.Custom(#<text>
#Ajax.ActionLink("Delete", "DeleteUserPreviousName", "Summary", null, null, new { id = item.Item.Id, #class = "deleteUserPreviousName" })
</text>).Encode(false);
})
.RowAttributes(p => new Hash(Id => "id"+p.Item.Index.ToString()))
.Attributes(Id => "userPreviousNamesTable")
.Empty("You currently have no Previous Names.")
.RenderUsing(new Tens.GridRenderers.UserPreviousNamesGridRenderer<Tens.Models.UserPreviousNamesView>()));
}
You could transform the model to add it a row index and then use the RowAttributes method:
#model IEnumerable<MyViewModel>
#(Html
.Grid(Model.Select((item, index) => new { Item = item, Index = index }))
.Columns(column =>
{
column.For(x => x.Item.Foo);
column.For(x => x.Item.Bar);
})
.RowAttributes(x => new Hash(id => string.Format("id{0}", x.Item.Index)))
)
Also I have pre-pended the id with the id keyword as ids in HTML cannot statr with a number as shown in your example.
Sample output:
<table class="grid">
<thead>
<tr>
<th>Foo</th>
<th>Bar</th>
</tr>
</thead>
<tbody>
<tr id="id0" class="gridrow">
<td>foo 1</td>
<td>bar 1</td>
</tr>
<tr id="id1" class="gridrow_alternate">
<td>foo 2</td>
<td>bar 2</td>
</tr>
<tr id="id2" class="gridrow">
<td>foo 3</td>
<td>bar 3</td>
</tr>
</tbody>
</table>
You can always show hide columns without adding id to particular row or columns like below
$(".mvcGridDollarHeader th:nth-child(16)").hide();
$(".mvcGrid td:nth-child(16)").hide();
Where mvcGrid is tableStyle and mvcGridDollarHeader is header style.
#grid1.GetHtml(
tableStyle: "mvcGrid",
displayHeader: true,
emptyRowCellValue: "",
headerStyle: "mvcGridDollarHeader",

error while trying to display view in asp.net mvc 3 app?

I am trying to display a list in a View, how to fix this error?
The model item passed into the dictionary is of type
'System.Data.Objects.ObjectQuery1[System.Linq.IGrouping2[System.Int32,mvc3Post.Models.Contact]]',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable`1[mvc3Post.Models.Contact]'.
controller:
public ActionResult Index()
{
AdventureWorksEntities db = new AdventureWorksEntities();
var result = from soh in db.SalesOrderHeaders
join co in db.Contacts
on soh.ContactID equals co.ContactID
orderby co.FirstName
group co by co.ContactID into g
select g;
return View(result.AsEnumerable());
}
view:
#model IEnumerable<mvc3Post.Models.Contact>
#{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
NameStyle
</th>
<th>
Title
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.NameStyle)
</td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ContactID }) |
#Html.ActionLink("Details", "Details", new { id = item.ContactID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ContactID })
</td>
</tr>
}
</table>
Updated now that I see the controller method:
You might need to transform your LINQ result set into a list or something (e.g., contacts.ToList()) more concrete.
Another alternative might be to create a root object for your page's list object to live on. I find it a little easier to follow and maintain if each View has a corresponding Model class that represents it's entire state.
I think either route will resolve your issue though. I think that the latter is probably the better way if I had to recommend one vs the other.

Resources