2

Basic problem is I'm new to asp.net mvc, my problem is to I want to pass the values to another view and update my details.While clicking the update button, now I could pass the normal values. But unable to pass dropdown values. Also I couldn't update my (sql) database as well. here is my code

1.index.cshtml

  <table class="table">
    <tr>
        <th>
            @Html.DisplayName("DepCode")
        </th>
        <th>
            @Html.DisplayName("CourseCode")
        </th>
        <th>
            @Html.DisplayName("SubjectCode")
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Room.RoomNo)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.date)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Day)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.StartTime)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FinishTime)
        </th>
        <th></th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Department.Code)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Course.Code)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Subject.Code)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Room.RoomNo)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.date)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Day)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.StartTime)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.FinishTime)
            </td>
            <td>                
                <input type="button" class="btn-primary btn-primary" title="Update" value="Update" onclick="location.href='@Url.Action("Edit", "AllocateClassRooms", new { id = item.Id })'" />
            </td>
        </tr>
    }
</table>

2.AllocateClassRoomsController.cs

 [HttpGet]
    public ActionResult Edit(int ID)
    {
       using (UniversityDbContext db=new UniversityDbContext())
        {

            ViewBag.SubjectID = new SelectList(db.Subjects, "SubjectID", "Code");
            ViewBag.CourseId = new SelectList(db.Courses, "Id", "Code");               
            ViewBag.DepartmentId = db.Departments.ToList();

            AllocateClassRoom allocateClassRoom = new AllocateClassRoom();

            allocateClassRoom.DepartmentId = getAllocationDetails.DepartmentId;
            allocateClassRoom.CourseId = getAllocationDetails.CourseId;
            allocateClassRoom.SubjectID = getAllocationDetails.SubjectID;
            allocateClassRoom.RoomId = getAllocationDetails.RoomId;
            allocateClassRoom.date = getAllocationDetails.date;
            allocateClassRoom.Day = getAllocationDetails.Day;
            allocateClassRoom.From = getAllocationDetails.From;
            allocateClassRoom.To = getAllocationDetails.To;
            allocateClassRoom.StartTime = getAllocationDetails.StartTime;
            allocateClassRoom.FinishTime = getAllocationDetails.FinishTime;

            return View(allocateClassRoom);

        }
    }
 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(AllocateClassRoom allocateClassRoom)
    {
        ViewBag.CourseId = new SelectList(db.Courses, "Id", "Code", allocateClassRoom.CourseId);
        ViewBag.SubjectID = new SelectList(db.Subjects, "SubjectID", "Code", allocateClassRoom.SubjectID);
        ViewBag.DepartmentId = db.Departments.ToList();
        ViewBag.RoomId = new SelectList(db.Rooms, "Id", "RoomNo", allocateClassRoom.RoomId);
        allocateClassRoom.StartTime = DateTime.ParseExact(allocateClassRoom.From, "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
        allocateClassRoom.FinishTime = DateTime.ParseExact(allocateClassRoom.To, "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay;

         db.Entry(allocateClassRoom).State = System.Data.Entity.EntityState.Modified;
         db.SaveChanges();
         return RedirectToAction("Index");

    }

3.Edit.cshtml

 @model UniversityMvcApp.Models.AllocateClassRoom
@if (Errormessage != null)
{
    <label>@Errormessage</label>
}
@if (allocatedMessage != null)
{
    <label>@allocatedMessage</label>
}
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        @Html.ValidationSummary(true)
        <div class="form-group">
            @Html.Label("Department Code", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
             <select name="DepartmentId" id="DepartmentId">                   
                    @foreach (var department in ViewBag.DepartmentId)
                    {
                        <option value="@department.ID">@department.Code</option>
                    }

                </select>
                @Html.ValidationMessageFor(model => model.CourseId)
            </div>
        </div>
        <div class="form-group">
            @Html.Label("Course Code", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <select name="CourseId" id="CourseId"></select>              
                @Html.ValidationMessageFor(model => model.CourseId)
            </div>
        </div>
        <div class="form-group">
            @Html.Label("Subject Code", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <select name="SubjectID" id="SubjectID"></select>                
                @Html.ValidationMessageFor(model => model.SubjectID)
            </div>
        </div>             
        <div class="form-group">
            @Html.LabelFor(model => model.RoomId, "Lecture Place", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <select name="RoomId" id="RoomId">                   
                    @foreach (var room in ViewBag.RoomId)
                    {
                        <option value="@room.Id">@room.RoomNo</option>
                    }

                </select>
                @Html.ValidationMessageFor(model => model.RoomId)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.date, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.date, new { @id = "Date" })
                @Html.ValidationMessageFor(model => model.date)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Day, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <select name="Day" id="Day">                  
                    <option value="Saturday">Saturday</option>
                    <option value="Sunday">Sunday</option>
                    <option value="Monday">Monday</option>
                    <option value="Tuesday">Tuesday</option>
                    <option value="Wednesday">Wednesday</option>
                    <option value="Thrusday">Thrusday</option>
                    <option value="Friday">Friday</option>
                </select>
                @Html.ValidationMessageFor(model => model.Day)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.From, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.From, new { @class = "From" })
                @Html.ValidationMessageFor(model => model.From)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.To, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.To, new { @class = "To" })
                @Html.ValidationMessageFor(model => model.To)
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Update" class="btn btn-success" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jquery")
    <script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.12.1.js"></script>
    <script>
        $(function () {
            $("#Date").datepicker({ dateFormat: 'dd-mm-yy' }).val;
        });
        $('.From,.To').timepicker({
            timeFormat: 'h:mm p',
            interval: 30,
            minTime: '8',
            maxTime: '6:00pm',
            defaultTime: '8',
            startTime: '8:00',
            dynamic: false,
            dropdown: true,
            scrollbar: true
        });
        $(document).ready(function () {           
            $("#DepartmentId").change(function () {
                var deptId = $("#DepartmentId").val();                
                $("#CourseId").empty();
                $("#CourseId").append('<option value="">Select</option>');
                var json = { DepartmentId: deptId };                
                $.ajax({
                    type: "POST",
                    url: '/AllocateClassRooms/GetCourseByDepartmentId',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(json),
                    success: function (data) {                        
                        $.each(data, function (key, value) {                           
                            $("#CourseId").append('<option value="' + value.Id + '">'
                                + value.Code + '</option>');

                        });
                    }
                });
            });
        });
        $(document).ready(function () {         
            $("#CourseId").change(function () {
                var courId = $("#CourseId").val();            
                $("#SubjectID").empty();
                $("#SubjectID").append('<option value="">Select</option>');
                var json = { CourseId: courId };       
                $.ajax({
                    type: "POST",                 
                    url: '/AllocateClassRooms/GetSubjectByCourseId',
                        contentType: "application/json; charset=utf-8",
                            data: JSON.stringify(json),
                                success: function (data) {                                   
                                    $.each(data, function (key, value) {
                             $("#SubjectID").append('<option value="' + value.SubjectID + '">' + value.Code + '</option>');                                       
                                    });
                                }
            });
        });
    });
    </script>
}
</div>

4.my model is AllocateClassRoom.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace UniversityMvcApp.Models
{
public class AllocateClassRoom
{
    public int Id { get; set; }

    public int DepartmentId { get; set; }
    public Department Department { get; set; }

    public int CourseId { get; set; }
    public Course Course { get; set; }

    public int SubjectID { get; set; }
    public Subject Subject { get; set; }


    public int RoomId { get; set; }
    public Room Room { get; set; }

    public DateTime date { get; set; }

    public string Day { get; set; }

    public string From { get; set; }

    public string To { get; set; }

    public TimeSpan StartTime { get; set; }

    public TimeSpan FinishTime { get; set; }

}
}

I put most important code as well, if anyone help me,it will be helpful.

Dilky
  • 85
  • 4

3 Answers3

0

Dilky

I think that using a Dropdownlist helper instead of creating the dropdown using a "for...each" statement could fix your problem.

Check out this link: How to write a simple Html.DropDownListFor()?

Regards

  • Though this link may provide valuable information it may be broken tomorrow. Please edit your answer and incorporate the condensed extract from your source into your answer so it stays useful without relying on external sources and we all can learn. – harmonica141 Sep 19 '19 at 10:07
  • 1
    thanks @cacatua_box ,it's little bit different approach compared to me. – Dilky Sep 19 '19 at 12:48
  • @harmonica141. Sorry, I'm quite noob answering in stackoverflow :) That link point to another question in stackoverflow. Should I edit the answer anyway? – cacatua_box Sep 19 '19 at 13:13
0

follow this approach it will be helpful and workout for your case. here is the link Also, inside your controller follow this code

[HttpGet]
public ActionResult Edit(int ID)
{
    using (UniversityDbContext db=new UniversityDbContext())
    {            
        ViewBag.SubjectID = new SelectList(db.Subjects, "SubjectID", "Code");
        ViewBag.CourseId = new SelectList(db.Courses, "Id", "Code");               
        ViewBag.DepartmentId = db.Departments.ToList();

        AllocateClassRoom allocateClassRoom = new AllocateClassRoom();

        allocateClassRoom.DepartmentId = getAllocationDetails.DepartmentId;
        allocateClassRoom.CourseId = getAllocationDetails.CourseId;
        allocateClassRoom.SubjectID = getAllocationDetails.SubjectID;
        allocateClassRoom.RoomId = getAllocationDetails.RoomId;
        allocateClassRoom.date = getAllocationDetails.date;
        allocateClassRoom.Day = getAllocationDetails.Day;
        allocateClassRoom.From = getAllocationDetails.From;
        allocateClassRoom.To = getAllocationDetails.To;
        allocateClassRoom.StartTime = getAllocationDetails.StartTime;
        allocateClassRoom.FinishTime = getAllocationDetails.FinishTime;

        var allocateClassRooms = db.AllocateClassRooms.Include(a => a.Course).Include(a => a.Department).Include(a => a.Subject).Include(a => a.Room).ToList();
        var getAllocationDetails = db.AllocateClassRooms.Where(s => s.Id == ID).FirstOrDefault();

        Department department = new Department();

        var departmnt = db.Departments.Where(s => s.ID == getAllocationDetails.DepartmentId).FirstOrDefault();
        ViewData["DepartmentData"] = departmnt.Code;

        var course = db.Courses.Where(s => s.Id == getAllocationDetails.CourseId).FirstOrDefault();
        ViewData["CourseData"] = course.Code;

        var subject = db.Subjects.Where(s => s.SubjectID == getAllocationDetails.SubjectID).FirstOrDefault();
        ViewData["subjectData"] = subject.Code;

        var room = db.Rooms.Where(x => x.Id == getAllocationDetails.RoomId).FirstOrDefault();
        ViewData["roomData"] = room.RoomNo;

        ViewData["DayValue"] = getAllocationDetails.Day;

        return View(allocateClassRoom);

    }
}

as well as your edit.cshtml follow this code

@model UniversityMvcApp.Models.AllocateClassRoom
@if (Errormessage != null)
{
    <label>@Errormessage</label>
}
@if (allocatedMessage != null)
{
    <label>@allocatedMessage</label>
}
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        @Html.ValidationSummary(true)
        <div class="form-group">
            @Html.Label("Department Code", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
              @{
                    var dep = ViewData["DepartmentData"];
                    var cou = ViewData["CourseData"];
                    var sub = ViewData["subjectData"];
                    var roo = ViewData["roomData"];
                    var day = ViewData["DayValue"];
                }


             <select name="DepartmentId" id="DepartmentId">
                    <option>@dep</option>
                    @foreach (var department in ViewBag.DepartmentId)
                    {
                        <option value="@department.ID">@department.Code</option>
                    }

                </select>
                @Html.ValidationMessageFor(model => model.CourseId)
            </div>
        </div>
        <div class="form-group">
            @Html.Label("Course Code", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <select name="CourseId" id="CourseId"><option>@cou</option></select>              
                @Html.ValidationMessageFor(model => model.CourseId)
            </div>
        </div>
        <div class="form-group">
            @Html.Label("Subject Code", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <select name="SubjectID" id="SubjectID"><option>@sub</option></select>                
                @Html.ValidationMessageFor(model => model.SubjectID)
            </div>
        </div>             
        <div class="form-group">
            @Html.LabelFor(model => model.RoomId, "Lecture Place", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <select name="RoomId" id="RoomId"> 
                    <option>@roo</option>
                    @foreach (var room in ViewBag.RoomId)
                    {
                        <option value="@room.Id">@room.RoomNo</option>
                    }

                </select>
                @Html.ValidationMessageFor(model => model.RoomId)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.date, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.date, new { @id = "Date" })
                @Html.ValidationMessageFor(model => model.date)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Day, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <select name="Day" id="Day">                  
                    <option value="Saturday">Saturday</option>
                    <option value="Sunday">Sunday</option>
                    <option value="Monday">Monday</option>
                    <option value="Tuesday">Tuesday</option>
                    <option value="Wednesday">Wednesday</option>
                    <option value="Thrusday">Thrusday</option>
                    <option value="Friday">Friday</option>
                </select>
                @Html.ValidationMessageFor(model => model.Day)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.From, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.From, new { @class = "From" })
                @Html.ValidationMessageFor(model => model.From)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.To, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.To, new { @class = "To" })
                @Html.ValidationMessageFor(model => model.To)
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Update" class="btn btn-success" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jquery")
    <script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.12.1.js"></script>
    <script>
        $(function () {
            $("#Date").datepicker({ dateFormat: 'dd-mm-yy' }).val;
        });
        $('.From,.To').timepicker({
            timeFormat: 'h:mm p',
            interval: 30,
            minTime: '8',
            maxTime: '6:00pm',
            defaultTime: '8',
            startTime: '8:00',
            dynamic: false,
            dropdown: true,
            scrollbar: true
        });
        $(document).ready(function () {           
            $("#DepartmentId").change(function () {
                var deptId = $("#DepartmentId").val();                
                $("#CourseId").empty();
                $("#CourseId").append('<option value="">Select</option>');
                var json = { DepartmentId: deptId };                
                $.ajax({
                    type: "POST",
                    url: '/AllocateClassRooms/GetCourseByDepartmentId',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(json),
                    success: function (data) {                        
                        $.each(data, function (key, value) {                           
                            $("#CourseId").append('<option value="' + value.Id + '">'
                                + value.Code + '</option>');

                        });
                    }
                });
            });
        });
        $(document).ready(function () {         
            $("#CourseId").change(function () {
                var courId = $("#CourseId").val();            
                $("#SubjectID").empty();
                $("#SubjectID").append('<option value="">Select</option>');
                var json = { CourseId: courId };       
                $.ajax({
                    type: "POST",                 
                    url: '/AllocateClassRooms/GetSubjectByCourseId',
                        contentType: "application/json; charset=utf-8",
                            data: JSON.stringify(json),
                                success: function (data) {                                   
                                    $.each(data, function (key, value) {
                             $("#SubjectID").append('<option value="' + value.SubjectID + '">' + value.Code + '</option>');                                       
                                    });
                                }
            });
        });
    });
    </script>
}
</div>

i think according to your code , it should workout for you

  • 1
    thanks a lot, it's work fine. but after that couldn't get the departmentId , courseId , subject id, room id value in the post method. why it happens like that? – Dilky Sep 19 '19 at 17:08
0

@Dilky i caught your problem, according to your model, foreign key conflict will happen, that's why you couldn't get those values.try this code in your controller post method.

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(AllocateClassRoom allocateClassRoom)
    {
            string subID = Request.Form["SubjectID"].ToString();
            var subject = db.Subjects.Where(s => s.Code == subID).FirstOrDefault();
            int departmentID = Convert.ToInt32(subject.DepartmentId);
            int CourseID = Convert.ToInt32(subject.SubCourForId);
            int SubjectID = subject.SubjectID;
            string roomNo = Request.Form["RoomId"].ToString();
            var room = db.Rooms.Where(s => s.RoomNo == roomNo).FirstOrDefault();
            int roomID = room.Id;
            allocateClassRoom.DepartmentId = departmentID;
            allocateClassRoom.CourseId = CourseID;
            allocateClassRoom.SubjectID = SubjectID;
            allocateClassRoom.RoomId = roomID;  

           allocateClassRoom.StartTime = DateTime.ParseExact(allocateClassRoom.From, "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
           allocateClassRoom.FinishTime = DateTime.ParseExact(allocateClassRoom.To, "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay;

         db.Entry(allocateClassRoom).State = System.Data.Entity.EntityState.Modified;
         db.SaveChanges();
         return RedirectToAction("Index");
    }