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:
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)
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.
I need to send to controller only those items that was changed by user. For example if first item Jhon changed to Jhon1 it should send, if it changed one more time to 'Jhon' it does not send. How to check this conditions? Use JQuery? For?
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/knockout-2.2.0.js"></script>
<h2>Index</h2>
<table>
<thead>
<tr>
<th>Passenger name</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td><input data-bind="value: name" /></td>
</tr>
</tbody>
</table>
<button data-bind="click: senddata">send</button>
<script>
function MyViewModel() {
var self = this;
self.items = ko.observableArray();
self.items.push({ name: 'Jhon' });
self.items.push({ name: 'Smith' });
self.senddata = function () {
var jsonOfLog = JSON.stringify(self.items());
debugger;
$.ajax({
type: 'POST',
url: 'Home/ConvertLogInfoToXml',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ jsonOfLog: jsonOfLog }),
dataType: 'json'
});
debugger;
}
}
ko.applyBindings(new MyViewModel());
Controller:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
public string ConvertLogInfoToXml(string jsonOfLog)
{
Console.WriteLine(jsonOfLog);
return Convert.ToString(jsonOfLog);
}
}
This is My KnockOut Controller Class
public class KnockoutController : Controller
{
//
// GET: /Knockout/
private DataLayer data;
public KnockoutController()
{
data=new DataLayer();
}
public ActionResult Index()
{
return View();
}
public ActionResult Grid()
{
ArrayList rows = new ArrayList();
List<Category> categories = data.RetrivingCategories();
foreach (var category in categories)
{
rows.Add(new { Id = category.Id, cell = new object[] { category.Id,
category.Name } });
}
var jsonData = new
{
rows
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
}
And This is My Index View
#{
ViewBag.Title = "Test";
}
<h2>Index</h2>
<title></title>
<script src="~/Scripts/jquery-ui-1.8.20.js"></script>
<script src="~/Scripts/knockout-2.1.0.debug.js"></script>
<script src="~/Scripts/knockout-2.1.0.js"></script>
<link href="~/Content/Site.css" rel="stylesheet" />
<table class="table">
<tr>
<th>
Key
</th>
<th>
Value
</th>
<th></th>
</tr>
<tbody data-bind="foreach: lookupCollection">
<tr>
<td data-bind="text: Key"></td>
<td data-bind="text: Value"></td>
</tr>
</tbody>
</table>
<script>
viewModel = {
lookupCollection: ko.observableArray()
};
$(function () {
$.ajax({
type: "GET",
url: "#Url.Action("Grid", "Knockout")",
}).done(function (data) {
$(data).each(function (index, element) {
var mappedItem =
{
Id: ko.observable(element.id),
Key: ko.observable(element.name),
};
viewModel.lookupCollection.push(mappedItem);
});
ko.applyBindings(viewModel);
}).error(function (ex) {
alert("Error");
});
});
</script>``
I am Calling json data from this index view using ajax call method but it's not returning anything, Any problem on my Script Part, Please help me , i am new to the Knockout..
Try this
$(function () {
$.ajax({
type: "GET",
url: "#Url.Action("Grid","Knockout")",
}).done(function (data) {
$.each(data, function (index, element) {
var mappedItem = {
Id: ko.observable(element.id),
Key: ko.observable(element.name),
};
viewModel.lookupCollection.push(mappedItem);
});
ko.applyBindings(viewModel);
}).error(function (ex) {
alert("Error");
});
});
From the jQuery API docs,
The $.each() function is not the same as $(selector).each(), which is
used to iterate, exclusively, over a jQuery object. The $.each()
function can be used to iterate over any collection, whether it is an object or an array.