In the past I wrote a small web application to register projects and adding employees working on that project. (with asp.net webpages)
Now I'm moving on to MVC3 and trying to recreate this webapp
I have two tables (with no relations to each other)
public partial class T_Project
{
public int id { get; set; }
[Required]
[Display(Name = "Project Name")]
public string ProjectName { get; set; }
[Display(Name = "Description")]
public string ProjectDiscription { get; set; }
[Display(Name = "Date")]
public DateTime ProjectDate { get; set; }
[Display(Name = "Begin Time")]
public TimeSpan ProjectBeginHoure { get; set; }
[DataType(DataType.Time)]
[Display(Name = "End Time")]
[TimeGreaterThanAttribute("ProjectBeginHoure")]
public TimeSpan ProjectEndHoure { get; set; }
public TimeSpan ProjectTotalTime { get; set; }
[Required]
public string ProjectEmployees { get; set; }
}
and
public partial class T_Employees
{
public int id { get; set; }
public string EmployeeName { get; set; }
}
}
(These are 2 different model classes)
Now in my webpages app i used to select the employees from a textbox and put them in another, then saved the employeenames (seperated by a comma in the projectemployees in my T_project Table
Tx! I'll try that, do you also have an idea how I can create 2 listboxes like in asp.net webpages? for example like this:
http://www.cstruter.com/blog/115
Tx! I'll try that, do you also have an idea how I can create 2 listboxes like in asp.net webpages? for example like this:
http://www.cstruter.com/blog/115
Kind regards,
Borrie
Hi
You can use jQuery to achieve it, just need to add this script in your project
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script language="javascript" type="text/javascript">
$(function() {
$("#MoveRight,#MoveLeft").click(function(event) {
var id = $(event.target).attr("id");
var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight";
var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft";
var selectedItems = $(selectFrom + " :selected").toArray();
$(moveTo).append(selectedItems);
selectedItems.remove;
});
});
</script>
[HttpPost]
public ActionResult Create(T_Project t_project)
{
if (ModelState.IsValid)
{
db.T_Project.Add(t_project);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(t_project);
}
I now want to update the db containing the employees from the selectrightbox, I have two tables with a many to many relationship, these are the model classes:
namespace MailServiceV3.Models
{
using System;
using System.Collections.Generic;
public class T_Employees
{
public int id { get; set; }
public string EmployeeName { get; set; }
public Nullable<bool> MFD { get; set; }
public virtual ICollection<T_Project> T_Project { get; set; }
}
}
namespace MailServiceV3.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class T_Project
{
public int id { get; set; }
[Required]
[Display(Name = "Project Name")]
public string ProjectName { get; set; }
[Display(Name = "Description")]
public string ProjectDiscription { get; set; }
[Display(Name = "Date")]
public System.DateTime ProjectDate { get; set; }
[Display(Name = "Begin Time")]
public System.TimeSpan ProjectBeginHoure { get; set; }
[Display(Name = "End Time")]
[TimeGreaterThanAttribute("ProjectBeginHoure")]
public System.TimeSpan ProjectEndHoure { get; set; }
public System.TimeSpan ProjectTotalTime { get; set; }
public virtual ICollection<T_Employees> T_Employees { get; set; }
}
}
So the save has to be done in the bridgetable T_ProjectEmployees, I don't have a modelclass for that (shouldn' be necessary) as my edmx schema sees it as a many to many relation
In the SelectLeft I'm passing in this: <option value="@emp.EmployeeID">@emp.EmployeeName</option>
So when I click on create the EmployeeID (which I think is also transferred into the selectright) together with the Project ID has to be inserted in my bridgetable T_ProjectEmployees
Ok, to add some extra info, in my edit function (I followed this tutorial: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/updating-related-data-with-the-entity-framework-in-an-asp-net-mvc-application) I'm able to save Employees from selectboxes.
This is the viewmodel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MailServiceV3.Viewmodels
{
public class SelectedEmployees
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public bool EmployeeSelected { get; set; }
}
}
[HttpPost]
public ActionResult Edit(int id, FormCollection formCollection, string[] selectedEmployeeBoxes)
{
var ProjectToUpdate = db.T_Project
.Include(i => i.T_Employees)
.Where(i => i.id == id)
.Single();
if (TryUpdateModel(ProjectToUpdate, "", null, new string[] { "T_Employees" }))
{
try
{
UpdateT_ProjectEmployees(selectedEmployeeBoxes, ProjectToUpdate);
db.Entry(ProjectToUpdate).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DataException)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
}
PopulateSelectEmployees(ProjectToUpdate);
return View(ProjectToUpdate);
}
private void UpdateT_ProjectEmployees(string[] SelectBoxEmployees, T_Project ProjectToUpdate)
{
if (SelectBoxEmployees == null)
{
ProjectToUpdate.T_Employees = new List<T_Employees>();
return;
}
var selectedEmployeesHS = new HashSet<string>(SelectBoxEmployees);
var ProjectEmployees = new HashSet<int>
(ProjectToUpdate.T_Employees.Select(c => c.id));
foreach (var employee in db.T_Employees)
{
if (selectedEmployeesHS.Contains(employee.id.ToString()))
{
if (!ProjectEmployees.Contains(employee.id))
{
ProjectToUpdate.T_Employees.Add(employee);
}
}
else
{
if (ProjectEmployees.Contains(employee.id))
{
ProjectToUpdate.T_Employees.Remove(employee);
}
}
}
}
So off course, this is way to much code - for the create function - because the functions have to check if an employeebox is already selected or not and according add or remove it to the table, but the functionality to add employees to the table is somewhere
in there :)
So any suggestions how I can save the employees from my selecright box into my database?
BorrieRulez
Member
18 Points
60 Posts
Moving on from webpages to MVC3
Apr 05, 2012 04:58 PM|LINK
Hey everyone,
In the past I wrote a small web application to register projects and adding employees working on that project. (with asp.net webpages)
Now I'm moving on to MVC3 and trying to recreate this webapp
I have two tables (with no relations to each other)
public partial class T_Project
{
public int id { get; set; }
[Required]
[Display(Name = "Project Name")]
public string ProjectName { get; set; }
[Display(Name = "Description")]
public string ProjectDiscription { get; set; }
[Display(Name = "Date")]
public DateTime ProjectDate { get; set; }
[Display(Name = "Begin Time")]
public TimeSpan ProjectBeginHoure { get; set; }
[DataType(DataType.Time)]
[Display(Name = "End Time")]
[TimeGreaterThanAttribute("ProjectBeginHoure")]
public TimeSpan ProjectEndHoure { get; set; }
public TimeSpan ProjectTotalTime { get; set; }
[Required]
public string ProjectEmployees { get; set; }
}
and
public partial class T_Employees
{
public int id { get; set; }
public string EmployeeName { get; set; }
}
}
(These are 2 different model classes)
Now in my webpages app i used to select the employees from a textbox and put them in another, then saved the employeenames (seperated by a comma in the projectemployees in my T_project Table
How can I do this in MVC3?
Tx,
Borrie
JohnLocke
Contributor
3216 Points
710 Posts
Re: Moving on from webpages to MVC3
Apr 05, 2012 05:14 PM|LINK
Here's how you can handle the delimited list:
You would create a string array and add all the names you've selected to the array.
Then, you can use String.Join() with "," to denote the delimiter, and include the array you created;
var employeeList = String.Join(",", myEmployeeNamesArray);
BorrieRulez
Member
18 Points
60 Posts
Re: Moving on from webpages to MVC3
Apr 05, 2012 06:14 PM|LINK
John,
Tx! I'll try that, do you also have an idea how I can create 2 listboxes like in asp.net webpages? for example like this: http://www.cstruter.com/blog/115
Kind regards,
Borrie
Young Yang -...
All-Star
21343 Points
1818 Posts
Microsoft
Re: Moving on from webpages to MVC3
Apr 10, 2012 10:00 AM|LINK
Hi
You can use jQuery to achieve it, just need to add this script in your project
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script> <script language="javascript" type="text/javascript"> $(function() { $("#MoveRight,#MoveLeft").click(function(event) { var id = $(event.target).attr("id"); var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight"; var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft"; var selectedItems = $(selectFrom + " :selected").toArray(); $(moveTo).append(selectedItems); selectedItems.remove; }); }); </script>You can get more details from here: http://www.dotnetcurry.com/ShowArticle.aspx?ID=458
Hope this helpful
Regards
Young Yang
Feedback to us
Develop and promote your apps in Windows Store
BorrieRulez
Member
18 Points
60 Posts
Re: Moving on from webpages to MVC3
Apr 10, 2012 11:06 AM|LINK
Young,
Thanks so much! It worked like a charm! I've updated the code to get the items dynamicly from my db.
I use a viewmodel for passing the items, when I call my create function I use this code to pass them to a viewbag:
public ActionResult Create() { PopulateEmptyEmployees(); return View(); } private void PopulateEmptyEmployees() { var allEmployees = db.T_Employees; var viewModel = new List<SelectedEmployees>(); foreach (var employee in allEmployees) { viewModel.Add(new SelectedEmployees { EmployeeID = employee.id, EmployeeName = employee.EmployeeName, EmployeeSelected = false }); } ViewBag.T_Employees = viewModel; }Then on the view I generate it like this:
<select id="SelectLeft" multiple="multiple"> @foreach (var emp in ViewBag.T_Employees) { <option value="@emp.EmployeeID">@emp.EmployeeName</option> } </select> <input id="MoveRight" type="button" value=" >> " /> <input id="MoveLeft" type="button" value=" << " /> <select id="SelectRight" multiple="multiple"> </select>and it works!
Do you know how i can then save it to my db?
The basic code I use is this:
[HttpPost] public ActionResult Create(T_Project t_project) { if (ModelState.IsValid) { db.T_Project.Add(t_project); db.SaveChanges(); return RedirectToAction("Index"); } return View(t_project); }I now want to update the db containing the employees from the selectrightbox, I have two tables with a many to many relationship, these are the model classes:
namespace MailServiceV3.Models
{
using System;
using System.Collections.Generic;
public class T_Employees
{
public int id { get; set; }
public string EmployeeName { get; set; }
public Nullable<bool> MFD { get; set; }
public virtual ICollection<T_Project> T_Project { get; set; }
}
}
namespace MailServiceV3.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class T_Project
{
public int id { get; set; }
[Required]
[Display(Name = "Project Name")]
public string ProjectName { get; set; }
[Display(Name = "Description")]
public string ProjectDiscription { get; set; }
[Display(Name = "Date")]
public System.DateTime ProjectDate { get; set; }
[Display(Name = "Begin Time")]
public System.TimeSpan ProjectBeginHoure { get; set; }
[Display(Name = "End Time")]
[TimeGreaterThanAttribute("ProjectBeginHoure")]
public System.TimeSpan ProjectEndHoure { get; set; }
public System.TimeSpan ProjectTotalTime { get; set; }
public virtual ICollection<T_Employees> T_Employees { get; set; }
}
}
So the save has to be done in the bridgetable T_ProjectEmployees, I don't have a modelclass for that (shouldn' be necessary) as my edmx schema sees it as a many to many relation
Do you know how this can be done?
ravikumarkam...
Member
20 Points
13 Posts
Re: Moving on from webpages to MVC3
Apr 10, 2012 11:08 AM|LINK
Hi BorrieRulez,
you can bind these two textboxes with MVC3 Razor syntax with the properties that you have mentioned.
For textbox binding Razor syntax :
BorrieRulez
Member
18 Points
60 Posts
Re: Moving on from webpages to MVC3
Apr 10, 2012 11:11 AM|LINK
ravikumarkamboj,
Can you specify it some more? how i can use that with my for loop? I'm new to mvc :)
ravikumarkam...
Member
20 Points
13 Posts
Re: Moving on from webpages to MVC3
Apr 10, 2012 11:22 AM|LINK
@{
foreach (var item in ItemList)
{
@Html.TextBoxFor(m => m.EmpName,item.Name, new{onclick="jsFunction()"}) // You can call any java script function to achieve your copy functionality.
}
}
@Html.TextBoxFor(m => m.EmpName)
BorrieRulez
Member
18 Points
60 Posts
Re: Moving on from webpages to MVC3
Apr 10, 2012 12:05 PM|LINK
ravikumarkamboj,
Sorry, I still don't get it, I need to get the items from my selectright object in the database
<select id="SelectRight" multiple="multiple">
</select>
In the SelectLeft I'm passing in this: <option value="@emp.EmployeeID">@emp.EmployeeName</option>
So when I click on create the EmployeeID (which I think is also transferred into the selectright) together with the Project ID has to be inserted in my bridgetable T_ProjectEmployees
BorrieRulez
Member
18 Points
60 Posts
Re: Moving on from webpages to MVC3
Apr 10, 2012 01:08 PM|LINK
Ok, to add some extra info, in my edit function (I followed this tutorial: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/updating-related-data-with-the-entity-framework-in-an-asp-net-mvc-application) I'm able to save Employees from selectboxes.
This is the viewmodel:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MailServiceV3.Viewmodels { public class SelectedEmployees { public int EmployeeID { get; set; } public string EmployeeName { get; set; } public bool EmployeeSelected { get; set; } } }The view file for edit:
<div class="editor-field"> <table> <tr> @{ int cnt = 0; List<MailServiceV3.Viewmodels.SelectedEmployees> employees = ViewBag.T_Employees; foreach (var employee in employees) { if (cnt++ % 3 == 0) { @: </tr> <tr> } @: <td> <input type="checkbox" name="selectedEmployeeBoxes" value="@employee.EmployeeID" @(Html.Raw(employee.EmployeeSelected ? "checked=\"checked\"" : "")) /> @employee.EmployeeID @: @employee.EmployeeName @:</td> } @: </tr> } </table> </div>and the controller functions:
[HttpPost] public ActionResult Edit(int id, FormCollection formCollection, string[] selectedEmployeeBoxes) { var ProjectToUpdate = db.T_Project .Include(i => i.T_Employees) .Where(i => i.id == id) .Single(); if (TryUpdateModel(ProjectToUpdate, "", null, new string[] { "T_Employees" })) { try { UpdateT_ProjectEmployees(selectedEmployeeBoxes, ProjectToUpdate); db.Entry(ProjectToUpdate).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } catch (DataException) { ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator."); } } PopulateSelectEmployees(ProjectToUpdate); return View(ProjectToUpdate); } private void UpdateT_ProjectEmployees(string[] SelectBoxEmployees, T_Project ProjectToUpdate) { if (SelectBoxEmployees == null) { ProjectToUpdate.T_Employees = new List<T_Employees>(); return; } var selectedEmployeesHS = new HashSet<string>(SelectBoxEmployees); var ProjectEmployees = new HashSet<int> (ProjectToUpdate.T_Employees.Select(c => c.id)); foreach (var employee in db.T_Employees) { if (selectedEmployeesHS.Contains(employee.id.ToString())) { if (!ProjectEmployees.Contains(employee.id)) { ProjectToUpdate.T_Employees.Add(employee); } } else { if (ProjectEmployees.Contains(employee.id)) { ProjectToUpdate.T_Employees.Remove(employee); } } } }So off course, this is way to much code - for the create function - because the functions have to check if an employeebox is already selected or not and according add or remove it to the table, but the functionality to add employees to the table is somewhere in there :)
So any suggestions how I can save the employees from my selecright box into my database?