In Model:
public int TeacherCourseAssignId { set; get; }
public int TeacherID { set; get; }
public decimal TeacherRemainingCredit { set; get; }
public int CourseId { set; get; }
public string CourseName { set; get; }
public decimal CourseCredit { set; get; }
In controller:
[HttpPost]
public ActionResult TeacherCourseAssign(int departmentId, int teacherId, int courseId)
{
ViewBag.Departments = GetDepartments();
return View();
}
public ActionResult SaveTeacherCourseAssign(TeacherCourseAssign teacherCourseAssign)
{
ViewBag.Departments = GetDepartments();
ViewBag.Message = teacherCourseAssignManager.Save(teacherCourseAssign);
ModelState.Clear();
return View();
}
public JsonResult SaveTeacheCourseAssign(TeacherCourseAssign teacherCourseAssign)
{
//Code
return Json(true, JsonRequestBehavior.AllowGet);
}
public JsonResult GetTeachersByDepartmentId(int deptId)
{
var teachers = GetTeacher();
var teacherList = teachers.Where(a => a.DepartmentId == deptId).ToList();
return Json(teacherList, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCoursesByDepartmentId(int deptId)
{
var courses = GetCourses();
var courseList = courses.Where(a => a.DepartmentId == deptId).ToList();
return Json(courseList, JsonRequestBehavior.AllowGet);
}
public JsonResult GetTeachersInfoByTeacherId(int teacherId)
{
var teachers = GetTeacher();
var teacherInfo = teachers.Where(t => t.TeacherID == teacherId).ToList();
return Json(teacherInfo, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCoursesInfoByCourseId(int courseId)
{
var courses = GetCourses();
var courseList = courses.Where(c => c.CourseId == courseId).ToList();
return Json(courseList, JsonRequestBehavior.AllowGet);
}
In View:
#model Last.Models.TeacherCourseAssign
#{
ViewBag.Title = "Teacher Course Assign";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Teacher Course Assign</h2>
<form method="POST" id="myForm">
<table>
<tr>
<td>
<label for="departmentId">Select Department</label>
</td>
<td>
<select name="departmentId" id="departmentId">
<option value="">Select...</option>
#foreach (var department in ViewBag.Departments)
{
<option value="#department.DeptId">#department.DeptName</option>
}
</select>
</td>
</tr>
<tr>
<td><label for="teacherId">Teacher</label></td>
<td>
<select name="teacherId" id="teacherId"></select>
</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.CreditToBeTaken)</td>
<td>#Html.TextBoxFor(m => m.CreditToBeTaken)</td>
</tr>
<tr>
<td>#Html.LabelFor(r => r.TeacherRemainingCredit)</td>
<td>
#Html.TextBoxFor(r => r.TeacherRemainingCredit)
</td>
</tr>
<tr>
<td><label for="courseId"></label></td>
<td>
<select name="courseId" id="courseId"></select>
</td>
</tr>
<tr>
<td>#Html.LabelFor(n => n.CourseName)</td>
<td>
#Html.TextBoxFor(n => n.CourseName)
</td>
</tr>
<tr>
<td>#Html.LabelFor(c => c.CourseCredit)</td>
<td>
#Html.TextBoxFor(c => c.CourseCredit)
<br>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" id="Submit" value="Assign" class="btn btn-default" /></td>
</tr>
</table>
</form>
#section scripts
{
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
$("#departmentId").change(function() {
var dept = $("#departmentId").val();
$("#teacherId").empty();
$("#courseId").empty();
var json = { deptId: dept };
//$("#teacherId").append('<option value="">Select</option>');
$.ajax({
type: "POST",
url: '#Url.Action("GetTeachersByDepartmentId", "TeacherCourseAssign")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function(data) {
$("#teacherId").append('<option value="">Select</option>');
$.each(data, function(key, value) {
$("#teacherId").append('<option value=' + value.TeacherID + '>' + value.TeacherName + '</option>');
});
}
});
// $("#courseId").append('<option value="">Select</option>');
$.ajax({
type: "POST",
url: '#Url.Action("GetCoursesByDepartmentId", "TeacherCourseAssign")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function(data) {
$("#courseId").append('<option value="">Select</option>');
$.each(data, function(key, value) {
$("#courseId").append('<option value=' + value.CourseId + '>' + value.CourseCode + '</option>');
});
}
});
});
$("#teacherId").change(function() {
var tech = $("#teacherId").val();
var json = { teacherId: tech };
$.ajax({
type: "POST",
url: '#Url.Action("GetTeachersInfoByTeacherId", "TeacherCourseAssign")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function(data) {
$.each(data, function(key, value) {
$("#CreditToBeTaken").val(value.CreditToBeTaken);
$("#TeacherRemainingCredit").val(value.CreditToBeTaken);
});
}
});
});
$("#courseId").change(function() {
var tech = $("#courseId").val();
var json = { courseId: tech };
$.ajax({
type: "POST",
url: '#Url.Action("GetCoursesInfoByCourseId", "TeacherCourseAssign")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function(data) {
$.each(data, function(key, value) {
$("#courseName").val(value.CourseName);
$("#CourseCredit").val(value.Credit);
});
}
});
});
});
</script>
}
My Cascading DropDown for department, course and teacher Info is working fine. but when I click on submit. it is not submitting any value to my post controller SaveTeacherCourseAssign(). want to know am i submitting my model in a wrong way?
Are you able to hit the controller at all? By default, all controllers actions listen to GET requests, so if you can't hit it, you would have to decorate it with [HttpPost] in order to hit it.
Also, I don't see any ajax request that's targeting it. Unless it's the form, at which point you might want to explicitly put an action attribute on it if the page/view name is not the same.
If you're in fact hitting a breakpoint when you submit, are you just getting a null object?
Alright, you have your form element but it doesn't have any action property. You have to add it like:
<form method="POST" id="myForm"
action="#Url.Action("your_action_method_name" , "your_controller_name")" >
I think this is what you are missing.
Related
I have a view model called "RequestGoodsBrandViewModel" and it's the combination of two models (Request and RequestGoodsBrand), I want to post a list of objects "RequestGoodsBrand" of view model " RequestGoodsBrandViewModel " from view to controller.
public class RequestGoodsBrandViewModel
{
public Request request{ get; set; }//single object of this
public List<RequestGoodsBrand> requestGoodsBrand { get; set; }//List of object of this
}
my view
<tbody>
<tr v-for="(data, index) in goods">
<td width="20%">
<select id="goodsDDL" class="form-control">
<option v-for="options in goodsList" :value="options.id">{{options.name}}</option>
</select>
</td>
<td width="20%">
<input type="number" v-model="data.quantity" id="quantityTxt" class="form-control" />
</td>
<td width="20%">
<select id="brandDDL" class="form-control">
<option v-for="options in brands" :value="options.id">{{options.name}}</option>
</select>
</td>
<td width="7%">
<a v-on:click="addRow(index)" class="btn"><i class="fa fa-plus-circle" style="color:darkgreen"></i></a>
<a v-on:click="removeRow(index)" class="btn"><i class="fa fa-minus-circle" style="color:red"></i></a>
</td>
</tr>
<tr>
<td colspan="4">
<label>توضیحات</label>
<textarea id="descTxt" class="form-control"></textarea>
</td>
</tr>
</tbody>
View looks like this and table is dynamic,by pressing plus button new row will be added
public IActionResult AddRequestedGoods(RequestGoodsBrandViewModel model)// only RequestGoodsBrand of RequestGoodsBrandViewModel must be a list
{
}
Edit:
I post my ViewModel to the controller using ajax call
var requestGoodsBrand = {}
var request = {
NeedDate: $('#needDate').val(),
Description: $('#descTxt').val(),
}
var table= document.getElementById('goodsTbl')
for (var i = 1; i < table.rows.length - 1; i++) {
requestGoodsBrand[i] = {
GoodsId:(table.rows[i].cells[0].children[0].value),
Quantity:(table.rows[i].cells[1].children[0].value),
BrandId:(table.rows[i].cells[2].children[0].value)
}
}
var model = {
"request": request,
"requestGoodsBrand": requestGoodsBrand,
}
console.log(model)
var data = JSON.stringify(model)
$.ajax({
type: "POST",
async: true,
url: '/GoodsRequest/AddRequestedGoods',
data: model,
//contentType: "application/json; charset=utf-8",
//dataType: "html",
success: function (data) {
}
});
the first object receives data but the second object which is a list, return null
Any solution?
i wrote a demo code for the same please on Jquery try it :
Jquery
function () {
var requestGoodsBrand = [];
var request = {
NeedDate: 'demo1',
Description: 'demo2',
}
$('table tr').each(function () {
var entity = {
GoodsId: $($(this).find('td:eq(0) input')).val(),
Quantity: $($(this).find('td:eq(1) input')).val(),
BrandId: $($(this).find('td:eq(2) input')).val()
};
requestGoodsBrand.push(entity);
})
$.post('/Home/AddRequestedGoods', { requestGoodsBrand: requestGoodsBrand, request: request })
.done(function (result) {
}
C#
[HttpPost]
public string AddRequestedGoods(Request request, List<RequestGoodsBrand> requestGoodsBrand)
{
return "";
}
I'm new to jQuery, here when I click the department code dropdown list then department name want to come inside the input field as well as I used jQuery function for that. the problem is to the department name didn't come while click the dropdown. I couldn't find out my mistake in my jQuery code, if anyone find out that it will be most helpful for me. Below, I saw my necessary code only
1.Create.cshtml
<tr class="spaceUnder">
<td>
<label for="departmentId">DepartmentCode</label>
</td>
<td>
<select name="departmentId" id="departmentId">
<option value="">Select...</option>
#foreach (var department in ViewBag.Departments)
{
<option value="#department.ID">#department.Code</option>
}
</select>
</td>
</tr>
<tr class="spaceUnder">
<td><label for="DepartmentName">DepName</label></td>
<td>
<input type="text" readonly="readonly" name="DepartmentName" id="DepartmentName" data-val="true">
</td>
</tr>
<script>
$(document).ready(function()
{
$('#departmentId').change(function ()
{
var DepId = $('#departmentId').val();
var json = { DepartmentId: DepId };
$.ajax(
{
type: "POST",
url: "/TeacherCourseAssign/GetDepartmentByDepartmentId",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function
(data) {
$('#DepartmentName').val(data.Name);
}
}
);
}
);
}
);
</script>
2.SubjectController.cs
public ActionResult Index()
{
var subjects = db.Subjects.Include(s => s.Department);
return View(subjects.ToList());
}
3.TeacherCourseAssignController.cs
public JsonResult GetDepartmentByDepartmentId(int departmentId)
{
List<Department> departments = aDepartmentManager.GetAllDepartments();
var department = departments.Find(a => a.ID == departmentId);
return Json(department);
}
4.DepartmentManager.cs
public List<Models.Department> GetAllDepartments()
{
return aDepartmentGateway.GetAllDepartment();
}
5.DepartmentGateway.cs
public List<Department> GetAllDepartment()
{
SqlConnection connection = new SqlConnection(connectionString);
string Query = "SELECT * FROM Departments ";
SqlCommand command = new SqlCommand(Query, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
List<Department> departments=new List<Department>();
while (reader.Read())
{
Department department = new Department()
{
ID=(int)reader["ID"],
Name = reader["Name"].ToString(),
Code=reader["Code"].ToString()
};
departments.Add(department);
}
reader.Close();
connection.Close();
return departments;
}
6.Subject.cs ( model )
public class Subject
{
public int SubjectID { get; set; }
[DisplayName("Department")]
public int? DepartmentId { get; set; }
[ForeignKey("DepartmentId")]
public virtual Department Department { get; set; }
[DisplayName("DepName")]
public string DepartmentName { get; set; }
}
i think, you made several mistake while writing the JQuery code.Try this, it might work for you.
#section scripts
{
<script>
$(document).ready(function()
{
$("#departmentId").change(function ()
{
var DepId = $("#departmentId").val();
var json = { DepartmentId: DepId };
$.ajax(
{
type: "POST",
url: '/TeacherCourseAssign/GetDepartmentByDepartmentId',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function
(data) {
$("#DepartmentName").val(data.Name);
}
}
);
}
);
}
);
</script>
}
then After try to Debugging JavaScript in your browser ,here you want to put the breakpoints appropriate place and find your solution as well.(More Details Debugging JavaScript in chrome.LinkHere)
How do I send some data from the view back to the controller?
This is the select from where I get the data (sel1):
<div class="form-group" style="margin: 0 auto;">
<label for="sel1">Select a cat breed:</label>
<select class="form-control" id="sel1">
#foreach (var item in Model)
{
<option>
#Html.DisplayFor(modelItem => item.BreedName)
</option>
}
</select>
</div>
This is the script I tried to use to send data back:
<script>
$(document).ready(function () {
loadJasonData();
$("#sel1").change(function () {
loadJasonData();
});
});
function loadJasonData() {
$.ajax({
type: "POST",
url: "CatDetails",
//url: "/CatCompare/CatDetails", i also tried this of url
cache: false,
dataType: "json",
data: { name: $("#sel1").val() }
})
}
And finally the controller:
[HttpPost]
[HttpGet]
public ActionResult CatDetails(string name)
{
var breedName = db.Breeds.FirstOrDefault(b => b.BreedName == name);
ViewBag.name = breedName.BreedName;
ViewBag.lifeSpan = breedName.Lifespan;
ViewBag.height = breedName.Height;
ViewBag.weight = breedName.Weight;
ViewBag.shortDescription = breedName.ShortDescription;
return View();
}
First of all you have to add option value to your select:
<div class="form-group" style="margin: 0 auto;">
<label for="sel1">Select a cat breed:</label>
<select class="form-control" id="sel1">
#foreach (var item in Model)
{
<option value='#item.BreedName'>
#Html.DisplayFor(modelItem => item.BreedName)
</option>
}
</select>
</div>
Then change your loadJasonData() method to this
function loadJasonData() {
$.ajax({
type: "POST",
url: "/CatCompare/CatDetails",
cache: false,
dataType: "json",
data: { name: $("#sel1 option:selected").val() }
})
}
at the last remove [HttpGet] in your action
[HttpPost]
public ActionResult CatDetails(string name)
{
var breedName = db.Breeds.FirstOrDefault(b => b.BreedName == name);
ViewBag.name = breedName.BreedName;
ViewBag.lifeSpan = breedName.Lifespan;
ViewBag.height = breedName.Height;
ViewBag.weight = breedName.Weight;
ViewBag.shortDescription = breedName.ShortDescription;
return View();
}
Note: Your action returns a view. If you want to return json result you have to use return Json(yourData);
I have ran into an issue of being unable to upload multiple files from nested models within the main knockout view model.
Testing out uploading HttpPostedFileBase properties, I was succesful in uploading a file and using two synchronous ajax calls within the EditTestStepjs file, using the XmlFile property.
However, in trying to send over multiple files that are bound to the nested models within the list, I am unable to have their values sent over to the controller using form-data.
Nested View Model
public class XmlParameterViewModel
{
public string ParameterName { get; set; }
public HttpPostedFileBase XmlValue { get; set; }
}
Main View Model
public class EditTestStepViewModel
{
public string TestStepName { get; set; }
public HttpPostedFileBase XmlFile { get; set; }
public List<XmlParameterViewModel> XmlParameters { get; set; }
public EditTestStepViewModel()
{
this.XmlParameters = new List<XmlParameterViewModel>();
}
}
Controller
[HttpPost]
public ActionResult SaveEdit(EditTestStepViewModel editTestStepViewModel)
{
return View("Index", editTestStepViewModel);
}
public JsonResult FileUpload(List<HttpPostedFileBase> xmlFile)
{
return Json(new {success = true}, JsonRequestBehavior.AllowGet);
}
EditTestStepJS file
var EditTestStepViewModel = function(data) {
var self = this;
ko.validatedObservable(ko.mapping.fromJS(data, mapping, self));
self.saveTestStep = function() {
if (self.isValid()) {
var file = new FormData($("#editForm").get(0));
$.ajax({
type: "POST",
url: "/Home/FileUpload/",
data: file,
processData: false,
contentType: false,
dataType: "json",
success: function () {
var dataToSend = ko.mapping.toJSON(self);
$.ajax({
url: "/Home/SaveEdit/",
type: "POST",
contentType: "application/json",
data: dataToSend
});
}
});
}
}
View
<form enctype="multipart/form-data" id="editForm">
<table class="table table-striped">
<tr>
<th>XmlPara</th>
</tr>
<tbody data-bind="foreach: XmlParameters">
<tr>
<td class="form-group"> <input name="ParameterName" class="form-control input-sm" data-bind="value: ParameterName" disabled="disabled"/></td>
<td class="form-group"> <input name="XmlValue" type="file" class="btn btn-group" data-bind="value: XmlValue" /></td>
</tr>
</tbody>
</table>
<button data-bind="click: saveTestStep" type="submit">Save Test Step</button>
<form>
I have a table in my View project ASP MVC
#foreach (var items in Model)
{
<tr>
<th>
<input type="button" value="Assign" onclick="AssignButtonClicked(this)"
data-assigned-id="#items.ADUsersId" />
</th>
<th>#Html.DisplayFor(modelItem => items.DisplayName)</th>
<th>#Html.DisplayFor(modelItem => items.Company)</th>
<th>#Html.DisplayFor(modelItem => items.Department)</th>
<th>#Html.DisplayFor(modelItem => items.TelephoneNumber)</th>
</tr>
}
In the first post I pass Id to the function JS
function AssignButtonClicked(elem) {
var id = $(elem).data('assigned-id');
$.ajax({
url: '#Url.Action("Details", "Users")',
type: 'post',
//cache: false,
//async: true,
//data: { id: id }
data: { id:id }, // OR data: {id:1} => nothing work
dataType: "json",
success: function (data) {
alert(JSON.stringify(data));
},
error: function (xhr) {
alert('error');
}
})
};
Everything works well, I get the JSON data
Now, How I can use the Json data to make details row in Datatable? Here Example
You can use a little bit of jQuery to display the details of the record.Here's a complete example, hope it helps you:
Controller:
public class UsersController : Controller
{
public ActionResult Index()
{
var u1 = new User { ADUsersId = 1, DisplayName = "User 1", Company = "Company 1" };
var u2 = new User { ADUsersId = 2, DisplayName = "User 2", Company = "Company 2" };
var u3 = new User { ADUsersId = 3, DisplayName = "User 3", Company = "Company 3" };
var users = new List<User> { u1, u2, u3 };
return View(users);
}
[HttpPost]
public JsonResult Details(int id)
{
//Write your query to fetch the details of the user(mine is hardcoded for simplicity)
return Json(new {UserSurname="Surname " + id,UserNickName="Nickname " + id }, JsonRequestBehavior.AllowGet);
}
}
public class User
{
public int ADUsersId { get; set; }
public string DisplayName { get; set; }
public string Company { get; set; }
}
View:
#model IEnumerable<WebApplication7.Controllers.User>
#{
ViewBag.Title = "Index";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<style type="text/css">
.detail{
border: 2px solid red;
}
</style>
<script type="text/javascript">
$('body').on('click', 'tr.detail', function () {
if(confirm("Are you sure you want to close the detail record?"))
{
$(this).remove();
}
});
function RemoveDetail(){
$('.table tr').each(function () {
var tr = $(this);
var isDetail = $(tr).hasClass("detail");
if (isDetail)
$(tr).remove();
});
}
function AssignButtonClicked(elem) {
var id = $(elem).data('assigned-id');
$.ajax({
url: '#Url.Action("Details", "Users")',
type: 'post',
data: { id: id },
dataType: "json",
success: function (data) {
debugger;
alert(JSON.stringify(data));
RemoveDetail();
var detailRow = "<tr class='detail'><td colspan='3'>Surname - " + data.UserSurname + "<br />Nickanme - " + data.UserNickName + "</td></tr>"
var currentRow = $(elem).parent().parent();
$(detailRow).insertAfter(currentRow);
},
error: function (xhr) {
alert('error');
}
});
};
</script>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.DisplayName)
</th>
<th>
#Html.DisplayNameFor(model => model.Company)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.DisplayName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Company)
</td>
<td>
<input type="button" value="Assign" onclick="AssignButtonClicked(this)" data-assigned-id="#item.ADUsersId" />
</td>
</tr>
}
</table>
Output: