I am doing my MVC application. I have a view that gets data from another view. This view is a form to fill.
public ActionResult AddGroupsQty(int qty, int id)
{
var model = new AddGroupsQtyViewModel();
model.subject_id = id;
model.qty = qty;
ClassDeclarationsDBEntities1 entities1=new ClassDeclarationsDBEntities1();
var subj = entities1.Subjects
.Where(b => b.class_id == model.subject_id)
.FirstOrDefault();
model.subject_name = subj.name;
if (ModelState.IsValid)
{
int maxId = 0;
int total = 0;
total = entities1.Groups.Count();
if (total == 0)
{
maxId = 0;
}
else
{
maxId = entities1.Groups.Max(u => u.group_id);
}
for (int i = 0; i < qty; i++)
{
var teacher = entities1.Users
.Where(b => b.email.Replace(" ", String.Empty) == model.teacher_emails[i].Replace(" ", String.Empty))
.FirstOrDefault();
var group=new Models.Group(id, maxId+1, model.group_names[i], teacher.user_id);
}
return RedirectToAction("OperationSuccess", "Account");
}
return View(model);
}
View model:
public class AddGroupsQtyViewModel
{
public int qty { get; set; }
public int subject_id { get; set; }
public string subject_name { get; set; }
[Required]
[Display(Name = "Name of group")]
public List<string> group_names { get; set; }
[Required]
[Display(Name = "Email of teacher")]
public List<string> teacher_emails { get; set; }
}
And finally my view:
#using System.IdentityModel.Configuration
#using System.Web.UI.WebControls
#model ClassDeclarationsThsesis.Models.AddGroupsQtyViewModel
#{
ViewBag.Title = "AddGroupsQty";
}
<h2>Add Groups to #Model.subject_name</h2>
#if (Model != null)
{
using (Html.BeginForm("AddGroupsQty", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Insert data</h4>
<hr />
<table>
<tr>
<th>
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.group_names, new { #class = "col-md-2 control-label" })
</div>
</th>
<th>
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.teacher_emails, new { #class = "col-md-2 control-label" })
</div>
</th>
</tr>
#for (int i = 0; i < Model.qty; i++)
{
<tr>
<th>
#Html.TextBoxFor(m => m.group_names[i], new { #class = "form-control" })
</th>
<th>
#Html.TextBoxFor(m => m.teacher_emails[i], new { #class = "form-control" })
</th>
</tr>
}
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit" />
</div>
</div>
}
}
What more or less it does is it takes qty and generates a table for this many rows. Then, the rows have text boxes to fill in, which should represent data from my View model. However, when I submit, I get such error:
The parameters dictionary contains a null entry for parameter 'qty' of
non-nullable type 'System.Int32' for method
'System.Web.Mvc.ActionResult AddGroupsQty(Int32, Int32)' in
'ClassDeclarationsThsesis.Controllers.AccountController'. An optional
parameter must be a reference type, a nullable type, or be declared as
an optional parameter. Nazwa parametru: parameters
How do I go about this problem?
You are not passing any value for qty after the form submission.
#Html.EditorFor(m => m.qty, new { #class = "form-control" })
#Html.HiddenFor(m=>m.id)
or
#using System.IdentityModel.Configuration
#using System.Web.UI.WebControls
#model ClassDeclarationsThsesis.Models.AddGroupsQtyViewModel
#{
ViewBag.Title = "AddGroupsQty";
}
<h2>Add Groups to #Model.subject_name</h2>
#if (Model != null)
{
using (Html.BeginForm("AddGroupsQty", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.HiddenFor(m=>m.qty) <%-- qty will be found my the controller after form submission --%>
#Html.HiddenFor(m=>m.id) <%-- id will also be found my the controller after form submission --%>
#Html.AntiForgeryToken()
<h4>Insert data</h4>
<hr />
<table>
<tr>
<th>
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.group_names, new { #class = "col-md-2 control-label" })
</div>
</th>
<th>
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.teacher_emails, new { #class = "col-md-2 control-label" })
</div>
</th>
</tr>
#for (int i = 0; i < Model.qty; i++)
{
<tr>
<th>
#Html.TextBoxFor(m => m.group_names[i], new { #class = "form-control" })
</th>
<th>
#Html.TextBoxFor(m => m.teacher_emails[i], new { #class = "form-control" })
</th>
</tr>
}
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit" />
</div>
</div>
}
}
Related
I have Friend view where are my Friends are listed inside a table as show in the picture below.
Now I have added new feature Add Friend so when I click on the the Link I am getting:
The resource cannot be found. HTTP 404
Here is my View where all friends are listed:
#using Lab3.Models
#model IEnumerable<Lab3.Models.FriendModel>
#{
ViewBag.Title = "Friends";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Friends</h2>
#Html.ActionLink("Add Friend", "AddNewFriend", "Friend", null, new { #class = "btn btn-primary" })
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Friend Id</th>
<th>Friend Name</th>
<th>Place</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (FriendModel friend in Model)
{
<tr>
<td>#friend.Id</td>
<td>#friend.Ime</td>
<td>#friend.MestoZiveenje</td>
<td>
#Html.ActionLink("Edit", "EditFriend", new { id = friend.Id }, null)
</td>
</tr>
}
</tbody>
</table>
The AddFriend view:
#model Lab3.Models.FriendModel
#{
ViewBag.Title = "AddFriend";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>AddFriend</h2>
#using (Html.BeginForm("AddNewFriend","Friend"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>FriendModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Ime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Ime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Ime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MestoZiveenje, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MestoZiveenje, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MestoZiveenje, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
And my the FriendController:
using Lab3.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Lab3.Controllers
{
public class FriendController : Controller
{
private static List<FriendModel> friendModels;
// GET: Friend
public ViewResult Index()
{
var friends = GetFriends();
return View(friends);
}
public ViewResult EditFriend(byte id)
{
var friend = GetFriends().SingleOrDefault(f => f.Id == id);
return View("EditFriend",friend);
}
[HttpPost]
public ActionResult AddNewFriend(FriendModel friend)
{
friendModels.Add(friend);
return View("Index", friendModels);
}
private IEnumerable<FriendModel> GetFriends()
{
return new List<FriendModel>
{
new FriendModel {Id = 1, Ime = "Marry", MestoZiveenje = "Dubai"},
new FriendModel {Id = 2, Ime = "John", MestoZiveenje = "London"},
new FriendModel {Id = 3, Ime = "Smith", MestoZiveenje = "Manchester"}
};
}
}
}
Why I am getting this 404 Error Page not found ?
The problem is that there is no action for your AddNewFriend View to redirect, a view should have a action with method get to redirect, and post methods are for once you submit the form in your view
Add below method in your controller it should solve the issue
[HttpGet]
public ActionResult AddNewFriend()
{
return View();
}
Error 404 means it can't find a route from your URL.
Check this line in your Razor page
#Html.ActionLink("Edit", "EditFriend", new { id = friend.Id }, null)
Here you are telling, When I click the link, Goto controller:"Edit" & action:"EditFriend".
This will resolve to "https://localhost/Edit/EditFriend?id=1"
But I can't find a EditController here and thus this link creates 404
Try putting "Friend" here because we have a "FriendController". Like
#Html.ActionLink("Friend", "EditFriend", new { id = friend.Id }, null)
This will resolve to "https://localhost/Friend/EditFriend?id=1"
My Get function works fine and the search textbox shows but when I enter the user ID and click search, it goes directly to the post function. It is supposed to go to the Get function again to show the data . after the data shows and whether I selected from the checkboxes or not, I click save and then it is supposed to go to the POst function.
What am I doing wrong?
GET function :
[HttpGet]
public ActionResult Index(int? SearchId)
{
var viewModel = new UserViewModel();
if (SearchId != null)
{
var userDepartments = db.TBL_User_Dep_Access.Where(x => x.UserID == SearchId).Select(x => x.Dep_ID).ToList();
List<UserDepartmentViewModel> udeptVM = db.TBL_Department.Select(i => new UserDepartmentViewModel
{
Dep_Id = i.Department_ID,
Dep_Name = i.Department_Name,
IsChecked_ = userDepartments.Contains(i.Department_ID)
}).ToList();
var userPermissions = db.TBL_UserPermissions.Where(x => x.UserID == SearchId).Select(m => m.PermissionID).ToList();
List<UsrPERViewModel> upVM = db.TBL_Permissions.Select(i => new UsrPERViewModel
{
Id = i.PermissionID,
Name = i.PermissionName,
IsChecked = userPermissions.Contains(i.PermissionID)
}).ToList();
viewModel.Departments = udeptVM;
viewModel.Permissions = upVM;
}
return View(viewModel);
}
My View:
#model Staff_Requisition.Models.UserViewModel
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<style>
.list-group {
max-height: 300px;
margin-bottom: 10px;
overflow: scroll;
-webkit-overflow-scrolling: touch;
}
</style>
#using (Html.BeginForm("Index", "TBL_UserPermission"))
{
#Html.AntiForgeryToken()
<body class="nav-md">
<div class="container body">
<div class="main_container">
<div class="title_right">
<div class="col-md-5 col-sm-5 col-xs-12 form-group pull-right top_search">
<div class="input-group">
#Html.TextBox("SearchId", "", null, new { #id = "SearchId", #placeholder = "Search for...", #class = "form-control" })
<span class="input-group-btn">
<input class="btn btn-default" value="Search" type="submit">Go! />
</span>
<ul>
#if (Model.Permissions != null)
{
foreach (var P in Model.Permissions)
{
<li>
<p>
#Html.CheckBoxFor(modelItem => P.IsChecked, new { #class = "flat", #value = P.IsChecked })
#Html.DisplayFor(modelItem => P.Name, new { #class = "DepartmentName", #value = P.Name })
#Html.HiddenFor(modelItem => P.Id, new { #class = "Dep_Id", #value = P.Id })
</p>
</li>
}
}
</ul>
<ul class="to_do">
#if (Model.Departments != null)
{
foreach (var D in Model.Departments)
{
<li>
<p>
#Html.CheckBoxFor(modelItem => D.IsChecked_, new { #class = "flat", #value = D.IsChecked_ })
#Html.DisplayFor(modelItem => D.Dep_Name, new { #class = "DepartmentName", #value = D.Dep_Name })
#Html.HiddenFor(modelItem => D.Dep_Id, new { #class = "Dep_Id", #value = D.Dep_Id })
</p>
</li>
}
}
</ul>
<div class="col-xs-12 col-sm-6 emphasis">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</body>
}
My POST function:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(UserViewModel user_Pers)
{
//remove user with specified ID from database
db.TBL_UserPermissions.RemoveRange(db.TBL_UserPermissions.Where(c => c.UserID == user_Pers.SearchId));
db.TBL_User_Dep_Access.RemoveRange(db.TBL_User_Dep_Access.Where(c => c.UserID == user_Pers.SearchId));
//for each permission that's checked add user to the table
foreach (var u in user_Pers.Permissions)
{
if (u.IsChecked)
{
TBL_UserPermissions Tup = new TBL_UserPermissions();
Tup.UserID = user_Pers.SearchId;
Tup.PermissionID = u.Id;
Tup.IsActive = true;
db.TBL_UserPermissions.Add(Tup);
}
}
db.SaveChanges();
foreach (var d in user_Pers.Departments)
{
if (d.IsChecked_)
{
TBL_User_Dep_Access Tud = new TBL_User_Dep_Access();
Tud.UserID = user_Pers.SearchId;
Tud.Dep_ID = d.Dep_Id;
Tud.IsActive = true;
db.TBL_User_Dep_Access.Add(Tud);
}
}
db.SaveChanges();
return RedirectToAction("myInfo");
}
BTW I removed most of the div in the view manually for simplicity, so it's okay if an opening or closing doesn't match.
As has been pointed out in the comments, in your code you have 1 form whereas to solve the problem you are talking about you need 2 forms. One form responsible for the search get request and the other responsible for the user post.
Here is a simple example of a search form and an update form on the same page.
The viewmodel and controller
using System.Web.Mvc;
namespace SearchAndSubmit.Controllers
{
public class UserViewModel
{
public int? Id { get; set; }
public string Name { get; set; }
}
public class HomeController : Controller
{
[HttpGet]
public ActionResult Edit(int? SearchId)
{
var viewModel = new UserViewModel();
if (SearchId != null)
{
viewModel.Id = SearchId;
//logic to search for user and create viewmodel goes here
}
return View(viewModel);
}
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Edit(UserViewModel user_Pers)
{
//validation and create update logic goes here
return RedirectToAction("Index");
}
}
}
The view
#model SearchAndSubmit.Controllers.UserViewModel
#{
ViewBag.Title = "Edit/create user";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>#ViewBag.Title</h2>
#*This is the search form it does a get request*#
#using (Html.BeginForm("edit", "home", FormMethod.Get))
{
#Html.TextBox("SearchId", "", null, new { #id = "SearchId", #placeholder = "Search for...", #class = "form-control" })
<span>
<input value="Search" type="submit">
</span>
}
#*This is the form for updating the user it does a post*#
#using (Html.BeginForm("edit", "home", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(c => c.Id)
<p>
#Html.LabelFor(c => c.Name)
#Html.TextBoxFor(c => c.Name)
</p>
<div>
<input type="submit" value="Save" />
</div>
}
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
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");
}
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
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
I have a table called SectionUser like:
SectionUser
USER_ID (varchar(255))(Primary Key)
NAME (varchar(255))
Here are sample values:
USER ID | NAME
EVTAB | ELMER TABER
FAYKVIL | FAYK VILLET
I have a create action in controller that can create a section user successfully. My main problem is that when I edit. I can't get the value. So for example, I've entered wrong USER_ID and I want to edit it. The USER_ID is always null. This means that I want to edit my primary key.
Controller:
public ActionResult EditUser(string USER_ID)
{
if (USER_ID == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SectionUser section = db.SectionUsers.Find(USER_ID);
if (section == null)
{
return HttpNotFound();
}
return View(section);
}
View(cshtml)
#using (Html.BeginForm("EditUser", "Admin", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Section</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.USER_ID)
<div class="form-group">
#Html.LabelFor(model => model.USER_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.USER_ID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.USER_ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NAME, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NAME, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NAME, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
View(Index)
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.USER_ID)
</th>
<th>
#Html.DisplayNameFor(model => model.NAME)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.USER_ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.NAME)
</td>
<td>
#Html.ActionLink("Edit", "EditUser", new { id = item.USER_ID.ToString().Trim() }) |
#Html.ActionLink("Details", "DetailsUser", new { id = item.USER_ID }) |
#Html.ActionLink("Delete", "DeleteUser", new { id = item.USER_ID })
</td>
</tr>
}
</table>
So my issue here is that the parameters I'm using on index.cshtml is wrong. This is the old code:
#Html.ActionLink("Edit", "EditUser", new { id = item.USER_ID.ToString().Trim() })
New Code:
#Html.ActionLink("Edit", "EditUser", new { USER_ID = item.USER_ID.ToString().Trim() })
As you can see in my EditUser Action, the parameter is string USER_ID.
I need to do a loop in another loop and I get a strange error as if it lacked a closing } and I get a compile error on the page. As against the project compiles . the error message is
CS1513 : } expected.
The source indicates the line of code in 1238 while I was not more than 150 lines of code in the page, really strange . help please
#using (Html.BeginForm("VCreateCommande", "CCommande", new { id = "formretouche" }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="control-label col-md-2">Support papier</div>
<div class="col-md-10">
#Html.CheckBoxFor(model => model.Tretouche.Supportpapier, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Tretouche.Supportpapier, "", new { #class = "text-danger" })
</div>
</div>
var i = 1;
foreach (var item in Model.Tformats)
{
var idformat = "idformat" + i;
var idquantite = "qteformat" + i;
var idtxt="qte" + #item.Idformat;
int qteretoucheformat=0;
foreach (var itemretoucheformat in Model.Tretouchesformats)
{
if(itemretoucheformat.IdFormat ==item.Idformat)
{
qteretoucheformat = itemretoucheformat.Quantité;
}
}
<div>
<div class="form-group">
<div class="control-label col-md-2 fltleft">Quantité #item.Format</div>
<div class="col-md-10 fltleft">
#Html.TextBoxFor(model => model.Tretoucheformat.Quantité, new { id = idtxt, Name=idtxt })
#Html.ValidationMessageFor(model => model.Tretoucheformat.Quantité, "", new { #class = "text-danger" })
</div>
</div>
</div>
i = i + 1;
}
<div class="form-group">
<div class="control-label col-md-2">Photo...</div>
<div class="col-md-10">
#Html.TextBoxFor(model => model.Tretouche.fichierphoto, new { type = "file" })
</div>
</div>
<input id="idtyperetouche" name="idtyperetouche" type="text" value="#idtyperetouche" class="hdn" />
<input name="idcommande" type="text" value="#idtyperetouche" class="hdn" />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Ajouter" class="btn btn-default" />
</div>
</div>
}
<table class="table">
<tr>
<th>Papier</th>
<th>Quantite</th>
<th>Type de retouche</th>
<th>Photo</th>
</tr>
#foreach (var item in Model.Tretouches)
{
var prix = 0;
<tr>
<td>
#Html.CheckBox("Papier", item.Supportpapier)
</td>
<td>
#Html.DisplayFor(modelItem => item.Quantite)
</td>
#foreach (var typeretouche in Model.Ttyperetouches)
{
if (item.Idtyperetouche == typeretouche.Idtyperetouche)
{
<td>#typeretouche.Libelle</td>
prix = (typeretouche.Prix * item.Quantite);
}
}
<td>
<img src="#item.SRCphoto" class="">
</td>
<td>
#prix €
</td>
<td>
#Html.ActionLink("Modifier", "Edit", "TRetouches", new { id = item.Idretouche }, null) |
#Html.ActionLink("Supprimer", "Delete", "TRetouches", new { id = item.Idretouche }, null)
</td>
</tr>
}
For Razor views (at least MVC 4 and earlier), unlike for a .cs file, the { needs to be on its own line
foreach (var itemretoucheformat in Model.Tretouchesformats)
{
}
Henk's comment suggests this may have been improved in MVC 5.