I am a beginner in programming being stuck the last 2 days on that and i am hopping on your help :)
I am building an mvc 4 app and I have a partial view with a list of departments and when you choose the department you can see the item types for this specific department in a drop down list in Browse view.
What I am trying to make is one more dropdown list in Browse view that will show the items according to the selected department and item types.
So this is my code :
View :
#using (Html.BeginForm("Browse", "Bookings", FormMethod.Post, new { id = "TypeItemFormID", data_itemsListAction = #Url.Action("ItemsList") }))
{
<fieldset>
<legend> Type/Item</legend>
#Html.DropDownList("department", ViewBag.ItemTypesList as SelectList, "Select a Type", new {id="ItemTypeID"})
<div id="ItemsDivId">
<label for="Items">Items </label>
<select id="ItemsID" name="Items"></select>
</div>
<p>
<input type ="submit" value="Submit" id="SubmitID" />
</p>
</fieldset>
}
<script src ="#Url.Content("~/Scripts/typeItems.js")"></script>
The controller :
public class BookingsController : Controller
{
private BookingSystemEntities db = new BookingSystemEntities();
//
// GET: /Bookings/
public ActionResult Index()
{
ViewBag.Message = "Select your Department";
var departments = db.Departments.ToList();
return View(departments);
}
public ActionResult Browse(string department, string ID)
{
ViewBag.Message = "Browse for Equipment";
var departments = db.Departments.Include("Items").Single(i => i.DepartmentName == department);
ViewBag.ItemTypesList = GetItemTypeSelectList(department);
return View();
}
public ActionResult Details(int id)
{
var item = db.Items.Find(id);
return View(item);
}
//
// GET: /Home/DepartmentMenu
[ChildActionOnly]
public ActionResult DepartmentMenu()
{
var departments = db.Departments.ToList();
return PartialView(departments);
}
public SelectList GetItemTypeSelectList(string department)
{
var departments = db.Departments.Include("Items").Single(i => i.DepartmentName == department);
List<SelectListItem> listItemTypes = new List<SelectListItem>();
foreach (var item in departments.Items.Select(s => s.ItemType.ItemTypeName).Distinct())
{
listItemTypes.Add(new SelectListItem
{
Text = item,
Value = item,
}
);
}
return new SelectList(listItemTypes.ToArray(),
"Text",
"Value");
}
public ActionResult ItemsList(string ID)
{
string Text = ID;
var items = from s in db.Items
where s.ItemType.ItemTypeName == Text
select s;
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
items.ToArray(),
"ItemId",
"ItemName")
, JsonRequestBehavior.AllowGet);
return RedirectToAction("Browse");
}
}
The Javascript :
$(function () {
$('#ItemsDivId').hide();
$('#SubmitID').hide();
$('#ItemTypeID').change(function () {
var URL = $('#TypeItemFormID').data('itemsListAction');
$.getJSON(URL + '/' + $('#ItemTypeID').val(), function (data) {
var items = '<option>Select a Item</option>';
$.each(data, function (i, item) {
items += "<option value='" + item.Value + "'>" + item.Text + "</option>";
// state.Value cannot contain ' character. We are OK because state.Value = cnt++;
});
$('#ItemsID').html(items);
$('#ItemsDivId').show();
});
});
$('#ItemsID').change(function () {
$('#SubmitID').show();
});
});
And at last my Model :
public class Department
{
public int DepartmentId { get; set; }
[DisplayName("Department")]
public string DepartmentName { get; set; }
public List<Item> Items { get; set; }
}
public class ItemType
{
public int ItemTypeId { get; set; }
[DisplayName("Type")]
public string ItemTypeName { get; set; }
[DisplayName("Image")]
public string ItemTypeImage { get; set; }
public List<Item> Items { get; set; }
}
public class Item
{
public int ItemId { get; set; }
[DisplayName("Name")]
public string ItemName { get; set; }
[DisplayName("Description")]
public string ItemDescription { get; set; }
[DisplayName("Ref Code")]
public string ItemReferenceCode { get; set; }
[ForeignKey("ItemType")]
public int ItemTypeId { get; set; }
public virtual ItemType ItemType { get; set; }
[ForeignKey("Department")]
public int DepartmentId { get; set; }
public Department Department { get; set; }
[DisplayName("Computer Location")]
public string ComputerLocation { get; set; }
[DisplayName("Author Name")]
public string AuthorName { get; set; }
[DisplayName("Published Year")]
public string PublishedYear { get; set; }
}
Here's how I would accomplish something like this. It isn't the only way to do it.
$('#ItemTypeID').on('change', function() {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#ItemTypeID').val() },
success: function(results) {
var options = $('#ItemTypeFormId');
options.empty();
options.append($('<option />').val(null).text("- Select an Item Type -"));
$.each(results, function() {
options.append($('<option />').val(this.ItemTypeFormId).text(this.Value));
});
}
});
});
Then you'd have a controller that looks something like this.
[HttpPost]
public JsonResult GetItemTypeForm(string itemTypeId)
{
//pseudo code
var data = Repostitory.GetData(itemTypeId)
return Json(data);
}
Related
I got a two DropDownList's in View. When i try pass those parameters, method in controller called but parameters equals a null.
When i check in browser (F12-network) i watch parameters - they are sended but in method still nulls
P.S.
I try change type of parameters on List or Location and JobTitle or CommonEntity, but its doesn't work
Controller:
public class HelloController: Controller
{
[HttpGet]
public IActionResult Index()
{
var locations = new List<Location>()
{
new Location()
{
Id = 0,
Title = "Russia"
},
new Location()
{
Id = 1,
Title = "Canada"
}
};
ViewBag.Location = locations;
var jobs = new List<JobTitle>()
{
new JobsTitle()
{
Id = 0,
Title = "Manager"
} ,
new JobsTitle()
{
Id = 1,
Title = "Programmer"
}
};
ViewBag.JobTitle = new SelectList(jobs, "Title", "Title");
return View();
}
[HttpPost]
public string Find(string answer1, string answer2)
{
return "Fine";
}
View:
#using Stargate.Core.Models.CoreEntities
#model CommonEntity
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.Location.Title, new SelectList(ViewBag.Location, "Title", "Title"))
#Html.DropDownListFor(m => m.JobTitle.Title, new SelectList(ViewBag.JobTitle, "Title", "Title"))
<button type="submit">Find</button>
}
Models:
public class CommonEntity
{
public Location Location { get; set; }
public JobTitle JobTitle { get; set; }
}
public class JobTitle
{
public long Id { get; set; }
public string Title { get; set; }
}
public class Location
{
public long Id { get; set; }
public string Title { get; set; }
}
Because the parameter names you accept are answer1, answer2, you should have a matching name in your view to make it possible to bind successfully.
You can modify your front-end code as follows(DropDownListForto DropDownList):
#model CommonEntity
#using (Html.BeginForm("Find", "Hello"))
{
#Html.DropDownList("answer1", new SelectList(ViewBag.Location, "Title", "Title"))
#Html.DropDownList("answer2", new SelectList(ViewBag.JobTitle, "Title", "Title"))
<button type="submit">Find</button>
}
Your Controller:
public class HelloController : Controller
{
[HttpGet]
public IActionResult Index()
{
var locations = new List<Location>()
{
new Location()
{
Id = 0,
Title = "Russia"
},
new Location()
{
Id = 1,
Title = "Canada"
}
};
ViewBag.Location = locations;
var jobs = new List<JobTitle>()
{
new JobTitle()
{
Id = 0,
Title = "Manager"
} ,
new JobTitle()
{
Id = 1,
Title = "Programmer"
}
};
ViewBag.JobTitle = jobs;
return View();
}
[HttpPost]
public string Find(string answer1,string answer2)
{
return "Fine";
}
}
Class:
public class CommonEntity
{
public Location Location { get; set; }
public JobTitle JobTitle { get; set; }
}
public class JobTitle
{
public long Id { get; set; }
public string Title { get; set; }
}
public class Location
{
public long Id { get; set; }
public string Title { get; set; }
}
Result:
you are doing things wrongly,
you should correct your cshtml so that when submitting the form, it will target your Find Action,
#using (Html.BeginForm("Find", "Hello"))
In your Find Action you should provide in input args resolvable by the DefaultModelBinder, since you don't have a ViewModel to intercept the response, I would suggest that you recieve a FormCollection and you can access your values from there.
[HttpPost]
public string Find(FormCollection form)
{
return "Fine";
}
Try updating parameters as below. Please refer Model Binding in ASP.NET Core for more details.
[HttpPost]
public string Find(Location Location, JobTitle JobTitle)
{
return "Fine";
}
Or you can try with parameter of CommonEntity like below.
[HttpPost]
public string Find(CommonEntity commonEntity)
{
var locationTitle = commonEntity.Location.Title;
var jobTitle = commonEntity.JobTitle.Title;
return "Fine";
}
error message:
http://prntscr.com/qtlodf
method:
public IActionResult GroepsResultaten(int vakId, int groepId)
{
var studentenLijst = _context.Student.Join(_context.StudentGroep,
s => s.Id,
sg => sg.StudentId,
(s, sg) => new { Student = s, StudentGroep = sg })
.Where(x => x.StudentGroep.GroepId == groepId)
.Select(x => x.Student);
ViewBag.Studenten = new SelectList(studentenLijst, "Id", "Naam");
return View();
}
I've also tried this:
public IActionResult GroepsResultaten(int vakId, int groepId)
{
var studentInfo = _context.Student
.Select(s =>
new
{
s.Id,
Naam = string.IsNullOrEmpty(s.Tussenvoegsel)
? s.Voornaam + " " + s.Achternaam + " - " + s.Studentnummer
: s.Voornaam + " " + s.Tussenvoegsel + " " + s.Achternaam + " - " + s.Studentnummer,
forStudent = s.Studentnummer + "-" + s.Achternaam
});
ViewBag.Studenten = new SelectList(studentInfo, "Id", "Naam");
return View();
}
I'm a bit stuck at this. I want to return multiple input fields (I'm just testing with selectlist at the moment) for all students of group x, from there on I want to be able to grade students for the subject that's included in the view using get method. Because English isn't my first language I've included two screenshots to clarify what I mean.
clarification of what I want to achieve:
group view: http://prntscr.com/qtlrqd
wireframe of method view: http://prntscr.com/qtlswn
models:
public class Student
{
public int Id { get; set; }
[Required]
public string Voornaam { get; set; }
[Required]
public string Achternaam { get; set; }
public string Tussenvoegsel { get; set; }
public string Studentnummer { get; set; }
public List<Resultaat> Resultaten { get; set; }
public List<StudentGroep> Groepen { get; set; }
}
public class Groep
{
public int Id { get; set; }
[Required]
public string Naam { get; set; }
[Required]
public string Groepscode { get; set; }
public List<GroepVak> Vakken { get; set; }
public List<StudentGroep> Studenten { get; set; }
}
public class StudentGroep
{
public Student Student { get; set; }
public int StudentId { get; set; }
public Groep Groep { get; set; }
public int GroepId { get; set; }
}
I hope I've included enough information, I'm available on discord too if that makes it easier.
The problem is what the SelectList class returns. Because view side results that ViewBag.Studenten is null.
Also, you must make sure that the database query returns a value.
Using ViewData resulted in what I want, from here on I can hopefully figure out how to use it for posting grades for each student.
Method:
public IActionResult GroepsResultaten(int vakId, int groepId)
{
var studentenLijst = _context.Student.Join(_context.StudentGroep,
s => s.Id,
sg => sg.StudentId,
(s, sg) => new { Student = s, StudentGroep = sg })
.Where(x => x.StudentGroep.GroepId == groepId)
.Select(x => x.Student)
.ToList();
if (groepId >= 1)
{
ViewData["Studenten"] = studentenLijst.ToList();
}
//ViewBag.Studenten = new SelectList(studentenLijst, "Id", "Naam");
return View();
}
View:
#foreach (var item in ViewBag.Studenten)
{
#item.Voornaam;
<input type="number" />
}
I am developing a simple website where there are students and there are courses. What is interesting is I can't seem to add a course to my student and make it save. I call the savechanges() method but on my cshtml page, my viewbag does not contain the updated student. Here is what I mean.
Here you can see my ViewBag.Student contains a valid student that has been modified to include two courses under PendingCourses. However, when I load my cshtml page, my ViewBag.Student contains:
So there is definitely some disconnect although I can't figure out what it is. So basically my Details page sets the ViewBag by doing a where statement on the context. This context is modified and saved with the AddCourseToStudent function and then the ViewBag.Student is read in the cshtml. Any help is much appreciated. Below are my files for reference.
Details Function:
// GET: Student/Details/5
[Authorize]
public ActionResult Details(int id)
{
using (var context = new StudentDbContext())
{
ViewBag.Student = context.Students.Where(u => u.id == id).FirstOrDefault();
}
var context2 = new ApplicationDbContext();
var userList = context2.Users.OrderBy(r => r.UserName).ToList().Select(rr => new SelectListItem { Value = rr.UserName.ToString(), Text = rr.UserName }).ToList();
ViewBag.Users = userList;
return View();
}
CSHTML:
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
SchoolRegistration.Models.Student student = ViewBag.Student;
List<SchoolRegistration.Models.Course> completedCourses = student.CompletedCourses;
List<SchoolRegistration.Models.Course> pendingCourses = student.PendingCourses;
List<SchoolRegistration.Models.Course> failedCourses = student.FailedCourses;
List<int> yearRange = new List<int>();
if (completedCourses != null) {
foreach (SchoolRegistration.Models.Course course in completedCourses)
{
if (!yearRange.Contains(course.Year))
{
yearRange.Add(course.Year);
}
}
}
if (pendingCourses != null)
{
foreach (SchoolRegistration.Models.Course course in pendingCourses)
{
if (!yearRange.Contains(course.Year))
{
yearRange.Add(course.Year);
}
}
}
if (failedCourses != null)
{
foreach (SchoolRegistration.Models.Course course in failedCourses)
{
if (!yearRange.Contains(course.Year))
{
yearRange.Add(course.Year);
}
}
}
yearRange.Sort();
}
<h2>Details</h2>
#if (TempData["Success"] != null)
{
if (TempData["Success"] == "nocourse")
{
<div style="background-color:aliceblue">
<p><strong>Success:</strong>Create Course?</p>
</div>
}
else
{
<div style="background-color:aliceblue">
<p><strong>Success:</strong> #TempData["Success"].ToString()</p>
</div>
}
}
<h3>#student.FirstName #student.LastName - #student.StudentID</h3>
<h4>#student.GradeLevel - #student.ExpectedGraduation</h4>
<h3>Degree Audit</h3>
#using (Html.BeginForm("GetCourse", "Student", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<p>Start Year: #Html.DropDownList("startYear", (IEnumerable<SelectListItem>)yearRange.ToList().Select(rr => new SelectListItem { Value = rr.ToString(), Text = rr.ToString() }).ToList(), "Select...") Start Semester: #Html.DropDownList("startSemester", EnumHelper.GetSelectList(typeof(SchoolRegistration.Models.Semesters)), "Select...")</p>
<p>End Year: #Html.DropDownList("endYear", (IEnumerable<SelectListItem>)yearRange.ToList().Select(rr => new SelectListItem { Value = rr.ToString(), Text = rr.ToString() }).ToList(), "Select...") End Semester: #Html.DropDownList("endSemester", EnumHelper.GetSelectList(typeof(SchoolRegistration.Models.Semesters)), "Select...")</p>
<input type="submit" value="Search" id="btnStudentFilter" />
}
<h3>Course Management</h3>
#using (Html.BeginForm("GetCourseForStudent", "Student", FormMethod.Post))
{
#Html.AntiForgeryToken();
<hr />
<p><strong>Subject: </strong>#Html.DropDownList("cat", EnumHelper.GetSelectList(typeof(SchoolRegistration.Models.Categories)), "Select...")</p>
<p><strong>CAT NO: </strong>#Html.TextBox("CourseId")</p>
<p><strong>Section: </strong>#Html.TextBox("SectionId")</p>
<p><strong>Year: </strong>#Html.TextBox("Year")</p>
<p><strong>Semester: </strong>#Html.DropDownList("semester", EnumHelper.GetSelectList(typeof(SchoolRegistration.Models.Semesters)), "Select...")</p>
<input type="submit" value="Search" />
}
#if (TempData["RetrievedCourses"] != null)
{
List<SchoolRegistration.Models.Course> courses = (List<SchoolRegistration.Models.Course>)TempData["RetrievedCourses"];
for (int i = 0; i < courses.Count; i++)
{
<p>#courses[i].Name - #courses[i].Category #courses[i].CourseId . #courses[i].SectionId - #courses[i].Credits Credits | #Html.ActionLink("Add to Student", "AddCourseForStudent", "Student", new { courseId = courses[i].id, studentId = student.id},null)</p>
}
<p>Course Search DIV Link</p>
}
AddCourseToStudent:
public ActionResult AddCourseForStudent(int courseId, int studentId)
{
using (var context = new StudentDbContext())
{
Student student = context.Students.Where(u => u.id == studentId).FirstOrDefault();
Course course = context.Courses.Where(u => u.id == courseId).FirstOrDefault();
List<Course> completed = student.CompletedCourses;
List<Course> pending = student.PendingCourses;
List<Course> failed = student.FailedCourses;
if (completed == null)
completed = new List<Course>();
student.CompletedCourses = completed;
if (pending == null)
pending = new List<Course>();
student.PendingCourses = pending;
if (failed == null)
failed = new List<Course>();
student.FailedCourses = failed;
pending.Add(course);
try
{
context.Entry(student).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
ViewBag.Student = student;
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
TempData["Success"] = "Courses added to student.";
return Redirect(Request.UrlReferrer.ToString());
}
Models:
public class InstructorViewModels
{
}
public enum GradeLevels
{
Freshman,
Sophmore,
Junior,
Senior,
Graduate
}
public enum Categories
{
CSCI
}
public enum Semesters
{
FA,
SP,
S1,
S2,
S3,
IN
}
public enum CourseTypes
{
Humanities
}
public class Student
{
public int id { get; set; }
[Required]
public int StudentID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string MiddleName { get; set; }
[Required]
public GradeLevels GradeLevel { get; set; }
[Required]
public List<Course> CompletedCourses { get; set; }
[Required]
public List<Course> PendingCourses { get; set; }
[Required]
public List<Course> FailedCourses { get; set; }
[Required]
public int ExpectedGraduation { get; set; }
}
public class Course
{
public int id { get; set; }
public int CourseId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int SectionId { get; set; }
[Required]
public Categories Category { get; set; }
[Required]
public int Credits { get; set; }
[Required]
public Semesters Semester { get; set; }
[Required]
public int Year { get; set; }
[Required]
public string InstructorId { get; set; }
public CourseTypes CourseType { get; set; }
}
Database:
I'm trying to pass few ViewModels to the same View via ViewData. Unfortunately I'm new to MVC and I do not have idea what's wrong with that.
Here is first DataViewModel:
public class TagsViewModel
{
public string TagName { get; set; }
public int TagId { get; set; }
}
And another one:
public class ShortPostViewModel
{
public int PostId { get; set; }
public string PostSubject { get; set; }
public DateTime? PostCreated { get; set; }
public string PostImage { get; set; }
public string PostAuthor { get; set; }
public byte? PostRating { get; set; }
public List<PostTagsViewModel> PostedTags { get; set; }
}
Here is repository:
public IEnumerable<BlogPostViewModel.ShortPostViewModel> GetLast20()
{
var last = from a in _db.blog_post
orderby a.Posted descending
select new BlogPostViewModel.ShortPostViewModel
{
PostId = a.ID,
PostAuthor = (from u in _db.users where u.ID == a.Author
select u.Login).FirstOrDefault(),
PostCreated = a.Posted,
PostImage = a.PostAvatar,
PostRating = a.Rating,
PostSubject = a.Subject,
PostedTags = (from b in _db.tags
join c in _db.posted_tags on b.ID equals c.TagID
where c.PostID == a.ID
select new PostTagsViewModel
{
TagId = b.ID,
TagName = b.TagName
}).ToList()
};
return last.Take(20);
}
And one more:
public IEnumerable<TagsViewModel> GetAll()
{
var t = from a in _db.tags
select new TagsViewModel
{
TagId = a.ID,
TagName = a.TagName
};
return t;
}
So here is Controller:
public ActionResult Index()
{
ViewData["ShortPost"] = _postRepository.GetLast20().AsEnumerable();
ViewData["Tags"] = _tagsRepository.GetAll().AsEnumerable();
return View();
}
So on the View:
<ul class="list-group">
#foreach (var item in (IEnumerable<ShortPostViewModel>)ViewData["ShortPost"])
{
<li class="list-group-item">
<img src="#item.PostImage" alt=""/>
<h3>#Html.ActionLink(#item.PostSubject, "Details", "BlogPost", new { id = item.PostId }, null)</h3>
Создано: #item.PostCreated. Автор: #item.PostAuthor. Оценка: #item.PostRating.
<p>
Темы статьи:
#foreach (var tag in #item.PostedTags)
{
<i class="glyphicon glyphicon-tag"></i> #Html.ActionLink(#tag.TagName, "Tag", "Search", new { id = tag.TagId }, null)
}
</p>
</li>
}
</ul>
</div>
<div class="col-md-4">
#foreach (var tag in (IEnumerable<TagsViewModel>)ViewData["Tags"])
{
<span class="label label-info"><i class="glyphicon glyphicon-tag"></i> #Html.ActionLink(#tag.TagName, "Tag", "Search", new { id = tag.TagId }, null)</span>
}
</div>
This all look just fine for me. Could you advise how should I fix that?
Instead of using several ViewData, I would recommend using a new ViewModel class that have a List<TagsViewModel> property and a List<ShortPostViewModel> property so you don't have to do the conversions in the view. Let's say the ViewModel is named CustomViewModel
public class CustomViewModel
{
public CustomViewModel()
{
this.ShortPosts = new List<ShortPostViewModel>();
this.Tags = new List<TagsViewModel>();
}
public List<ShortPostViewModel> ShortPosts { get; set; }
public List<TagsViewModel> Tags { get; set; }
}
then in your controller
public ActionResult Index()
{
CustomViewModel model = new CustomViewModel();
model.ShortPosts = _postRepository.GetLast20().ToList();
model.Tags = _tagsRepository.GetAll().ToList();
return View(model);
}
Make sure you have this at the top of your view code
#model CustomViewModel
You can enumerate the items of ShortPosts in your view as below
#foreach (var item in Model.ShortPosts)
and enumerate the items of Tags as below
#foreach (var tag in Model.Tags)
I have this problem where i want to make 7 dropdowns for each day of the week.
In each one of those dropdowns i wish to add the same data.
My ViewModel:
public class WeekDienstCreateViewModel
{
public WeekDienst weekDienst {get; set;}
public List<DienstPerWeekDienst> diensten { get; set; }
public WeekDienstCreateViewModel() { }
}
My Create Method in Controller:
As u can see I add everything allready except DienstId which is want to add with my dropdowns.
public ActionResult Create(int id)
{
WeekDienst wd = _service.FindWeekDienst(id);
WeekDienstCreateViewModel vm = new WeekDienstCreateViewModel();
vm.diensten = new List<DienstPerWeekDienst>();
vm.weekDienst = wd;
for (int i = 1; i <= 7; i++)
{
DienstPerWeekDienst dpwd = new DienstPerWeekDienst();
dpwd.volgnummer = i;
dpwd.WeekDienstId = wd.Id;
vm.diensten.Add(dpwd);
}
ViewBag.Diensten = _service.DienstenList(wd.AfdelingId);
return View(vm);
}
Classes:
public class DienstPerWeekDienst
{
[Key]
public int Id { get; set; }
[Required]
public int WeekDienstId { get; set; }
[Required]
public int DienstId { get; set; }
[Required]
[Range(1, 7)]
public int volgnummer { get; set; }
[ForeignKey("WeekDienstId")]
public virtual WeekDienst WeekDienst { get; set; }
[ForeignKey("DienstId")]
public virtual Dienst Dienst { get; set; }
public virtual ICollection<WeekDienst> WeekDiensten { get; set; }
}
public class WeekDienst
{
[Key]
public int Id { get; set; }
[Required]
public int AfdelingId { get; set; }
[Required]
[StringLength(5, ErrorMessage = "Value for {0} cannot exceed {1} characters.")]
[RegularExpression(#"^[a-zA-Z0-9]{5}$", ErrorMessage = "Verplicht 5 cijfers lang.")]
public string code { get; set; }
[DisplayName("Template")]
public bool template { get; set; }
[ForeignKey("AfdelingId")]
public virtual Afdeling Afdeling { get; set; }
}
And in my view i wish to create 7 dropdowns where i put in all my "Diensten" (class Dienst, fk in DienstPerWeekDienst). When I choose 1 i wish to add the "DienstId" into the "DienstPerWeekDienst" class.
So in my View i got this:
#foreach (var day in Model.diensten)
{
var currentDay=day;
#Html.DropDownListFor(currentDropDown=>currentDay, new SelectList(ViewBag.Diensten, "Value", "Text"))
}
I Wish to postback the chosen "Diensten" and create the "WeekDienst" but now i am just posting a null "DienstPerDienstWeekCreateViewModel". How am I able to fix this?
Thanks in Advance
FIX (Thanks to Siva Gopal)
I fixed this by doing:
#for (int i = 0; i < #Model.diensten.Count; i++)
{
#Html.HiddenFor(m => (m.diensten[i].volgnummer))
#Html.HiddenFor(m => (m.diensten[i].WeekDienstId))
#Html.DropDownListFor(m=> (m.diensten[i].DienstId), new SelectList(ViewBag.Diensten, "Value", "Text"))
}
You may try using
#foreach (var day in Model.diensten)
{
var currentDay=day;
#Html.DropDownListFor(currentDropDown=>currentDay, new SelectList(ViewBag.Diensten, "PropertyName_Holding_Value", "PropertyName_Holding_DisplayText"), new { })
} //This uses the Lambda Expression. Your dropdown Name/Id would be 1,2,3 etc. based on currentDay value.
OR
#foreach (var day in Model.diensten)
{
var currentDay=day;
var dropdownName=string.Format("diensten[{0}]",day-1); //If you want to model bind the selected dropdown value to input entity in POST request. The final dropdownName format should match the hierarchy of the property inside input entity/object. Even without this name formation, you can still POST the selected value back using Jquery/Javascript.
#Html.DropDownList(dropdownName, new SelectList(ViewBag.Diensten, "PropertyName_Holding_Value", "PropertyName_Holding_DisplayText"), new {})
} //
Note for Value Post back/model bind on full Page submit:
To be able to model bind/POST back values to the server, the html element names corresponding to the properties should be rendered as follows: Suppose if you display Employee.Department.Name, then name of textbox, displaying the Department Name in View should match Department_ReferenceName_Inside_Employee.Name for model binding.
Model:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public Department EmpDepartment { get; set; }
public List SubOrdinates { get; set; }
}
public class Department
{
public string Name { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
//Prepare the model and send it to the view
Employee emp = new Employee { EmpDepartment = new Department { Name = "IT" } };
emp.SubOrdinates = new List<Employee> { new Employee { Name = "Emp1" }, new Employee { Name = "Emp2" } };
return View(emp);
}
[HttpPost]
public ActionResult Index(Employee emp)
{ //Put a break-point here and see how the modified values in view are flowing into emp..
return View(emp);
}
public ActionResult About()
{
return View();
}
}
View:
#model MvcApplication.Models.Employee
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.EmpDepartment.Name)
#Html.LabelForModel("SubOrdinates :")
for (int i = 0; i < #Model.SubOrdinates.Count; i++)
{
#Html.TextBoxFor(m => (m.SubOrdinates[i].Name))
}
<input type="submit" name="name" value="Submit" /> }
ViewSource/PageSource:
The above text box syntax will be rendered as :
<input id="EmpDepartment_Name" name="EmpDepartment.Name" type="text" value="IT" /> <!--See above html : name=EmpDepartment.Name -->
<label for="">SubOrdinates :</label>
<input id="SubOrdinates_0__Name" name="SubOrdinates[0].Name" type="text" value="Emp1" />
<input id="SubOrdinates_1__Name" name="SubOrdinates[1].Name" type="text" value="Emp2" /> <!--See above html for how collection item Name(s) are being renderd by view engine-->
<input type="submit" name="name" value="Submit" />
#foreach (var day in Model.diensten)
{
var currentDay = day;
#Html.DropDownListFor(x => currentDay, new SelectList(ViewBag.Diensten, "Value", "Text"), new { #id = "DienstList" })
}
List<MvcApplication1.Models.Country> cntry = db.Countries.ToList();
SelectListItem sss = new SelectListItem();
List<SelectListItem> sltst = new List<SelectListItem>();
sss.Text = "Select";
sss.Value = "0";
sltst.Add(sss);
foreach (MvcApplication1.Models.Country s in cntry){
SelectListItem s1 = new SelectListItem();
s1.Text = s.Country1;
s1.Value = Convert.ToString(s.Id);
sltst.Add(s1);}
#Html.DropDownList("country", sltst, new { #id = "country" })