Im trying serialize form and binding into model, but some how child of model InsertToUsertbls returns NULL. Can any help me please :)
I have the following model:
public class MangeAddUsers
{
public List<InsertToUsertbl> InsertToUsertbls { get; set; }
public class InsertToUsertbl
{
public InsertToUsertbl()
{
}
public int PX2ID { get; set; }
public string CustomerNR { get; set; }
public string SellerPersonCode { get; set; }
public string NameOfCompany { get; set; }
public string CompanyNo { get; set; }
}
}
JavaScript to Get data and than load them into form:
<script>
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function myfunction() {
$.ajax({
type: "GET",
url: "/Account/GetCustomerContactInfo",
data: {ids: '10883'},
dataType: 'json',
traditional: true,
success: function (values) {
var holderHTML = "";
for (var i = 0; i < values.length; i++) {
value = values[i]
if (value != null) {
var guid = uuidv4();
holderHTML += '<tr id="row' + value.CustomerNo + '">';
holderHTML += '<input type="hidden" name="InsertToUsertbls.Index" value="' + guid + '" />';
holderHTML += '<td><input class="inpt-tbl" type="hidden" id="CustomerNR" name="InsertToUsertbls[' + guid + '].CustomerNR" value="' + value.CustomerNo + '" /></td>';
holderHTML += '<td><input class="inpt-tbl" type="hidden" id="NameOfCompany" name="InsertToUsertbls[' + guid + '].NameOfCompany" value="' + value.NameOfCompany + '" /></td>';
holderHTML += '<td><input type="hidden" id="CompanyNo" name="InsertToUsertbls[' + guid + '].CompanyNo" value="' + value.CompanyNo + '" /></td>';
holderHTML += '<input type="hidden" id="SellerPersonCode" name="InsertToUsertbls[' + guid + '].SellerPersonCode" value="' + value.SalgePersonCode + '" />';
holderHTML += '</tr>';
}
}
$('#output').append(holderHTML);
},
error: function () {
console.log('something went wrong - debug it!');
}
})
};
</script>
And when data load into form:
<form id="mangeUserFrom">
<div id="output">
<tr id="row10883">
<input type="hidden" name="InsertToUsertbls.Index" value="fd3424ab-160d-4378-af65-ad2b790812ec">
<td>
<input class="inpt-tbl" type="hidden" id="CustomerNR" name="InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].CustomerNR" value="10883">
</td>
<td>
<input class="inpt-tbl" type="hidden" id="NameOfCompany" name="InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].NameOfCompany" value="Some Name">
</td>
<td>
<input type="hidden" id="CompanyNo" name="InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].CompanyNo" value="849">
</td>
<input type="hidden" id="SellerPersonCode" name="InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].SellerPersonCode" value="TT">
</tr>
</div>
</form>
<button type="button" id="createuser" onclick="PostForm();">POST</button>
JavaScript for serializing:
<script>
function PostForm() {
var formdata = $("#mangeUserFrom").serializeArray();
console.log(formdata);
$.ajax({
"url": '#Url.Action("MangeCreateUsers", "Account")',
"method": "POST",
"data": formdata,
"dataType": "json",
success: function (data) {
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
</script>
This is the result of the serialization:
{name: "InsertToUsertbls.Index", value: "fd3424ab-160d-4378-af65-ad2b790812ec"}
{name: "InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].CustomerNR", value: "10883"}
{name: "InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].NameOfCompany", value: "Some Name"}
{name: "InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].CompanyNo", value: "849"}
{name: "InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].SellerPersonCode", value: "TT"}
This is my controller method I'm trying to POST to:
[HttpPost]
public JsonResult CreateCustomers(CreateCustomers model)
{
return Json(model, JsonRequestBehavior.AllowGet);
}
Screenshots:
Related
I am trying to create a search filter, each time I insert data type an int, it throws an error to below line and need some help, as to how to resolve it.
When I step into the method Json GetStringData where error is thrown, I saw the 'SearchValue' is undefined.
How does this become possible? How can I change this in order for this code to work? As in where the error is thrown, the data does come back from record, the issue is when search filter is inserted.
ASP.Net
//GET: SearchPeople-ID.
public ActionResult SearchPeopleDetails()
{
RegCoursesViewModel regCoursesView = new RegCoursesViewModel();
return View(cb.RegPeopleLists.ToList());
}
// GET://Passing-Data-Back as Json.
public JsonResult GetSearchingData(string SearchBy, string SearchValue)
{
List<eNtsaRegPeopleLists> regPeopleLists = new List<eNtsaRegPeopleLists>();
if(SearchBy == "ID")
{
try
{
int Id = Convert.ToInt32(SearchValue); // Incorrect string format
regPeopleLists = cb.RegPeopleLists.Where(v => v.LoginID == Id || SearchValue == null).ToList();
}catch(FormatException)
{
Console.WriteLine("{0} Is Not A ID ", SearchValue);
}return Json(regPeopleLists, JsonRequestBehavior.AllowGet);
}
else
{
regPeopleLists = cb.RegPeopleLists.Where(v => v.Name.StartsWith(SearchValue) || SearchValue == null).ToList();
return Json(regPeopleLists, JsonRequestBehavior.AllowGet);
}
}
public class eNtsaRegPeopleLists
{
public string Name { get; set; }
[Key]
public int LoginID { get; set; }
public string SISID { get; set; }
public string Role { get; set; }
public DateTime LastActivity { get; set; }
public decimal TotalActivity { get; set; }
}
Javascript
<!--Javascript functionality for filter search-->
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#SearchLv").keyup(function () {
var SearchBy = $("#SearchBy").val();
var SearchValue = $("#Search").val();
var SetData = $("#DataSearching");
SetData.html("");
debugger;
$.ajax({
type: "post",
url: "/Home/GetSearchingData?SearchBy=" + SearchBy + "&SearchValue=" + SearchValue,
contentType: "html",
success: function (result) {
if (result.length == 0) {
SetData.append('<tr style="color:red"><td colspan="3">No Match Data</td></tr>')
}
else {
$.each(result, function (index, value) {
var Data = "<tr>" +
"<td>" + value.LoginID + "</td>" +
"<td>" + value.Name + "</td>" +
"<td>" + value.Role + "</td>" +
"<td>" + value.SIS_ID + "</td>" +
"<td>" + value.LastActivity + "</td"> +
"<td>" + value.TotalActivity + "</td>"
"</tr>";
SetData.append(Data);
});
}
}
});
});
});
</script>
View
#model IEnumerable<eNtsaRegistrationTraining.Models.eNtsaRegPeopleLists>
<br />
<br />
<div class="form-group row float-right">
<form class="form-group ml-lg-auto">
<div class="input-group input-group-sm">
<input class="form-control form-control-navbar" type="search" placeholder="Search" aria-label="Search" id="SearchLv">
<div class="input-group-append">
<button class="btn btn-navbar" type="submit">
<i class="fas fa-search"></i>
</button>
</div>
</div>
</form>
</div>
<!--Select-ID-->
<select id="SearchBy">
<option value="ID">LoginID</option>
<option value="Name">Name</option>
<option value="Roles">Roles</option>
</select>
<br />
<br />
<table class="table table-bordered">
<thead>
<tr>
<th>LoginID</th>
<th>Name</th>
<th>Roles</th>
<th>SISID</th>
<th>LastActivity</th>
<th>TotalActivity</th>
</tr>
</thead>
<!--Tbody here-->
<tbody id="DataSearching">
#foreach(var Item in Model)
{
<tr>
<td>#Item.LoginID</td>
<td>#Item.Name</td>
<td>#Item.Role</td>
<td>#Item.SISID</td>
<td>#Item.LastActivity</td>
<td>#Item.TotalActivity</td>
</tr>
}
</tbody>
</table>
search input id is {SearchLv} in your view.
<input class="form-control form-control-navbar" type="search" placeholder="Search" aria-label="Search" id="SearchLv">
Either change the id in view
<input class="form-control form-control-navbar" type="search" placeholder="Search" aria-label="Search" id="Search">
Or you can change on javascript
var SearchValue = $("#SearchLv").val();
I have a function and get the response from the controller.after that I need to append the details to the table.All I have done.But i can see the result only after I click the table .I think my datatable is not reloaded.How Can I solve this problem.My code is below.and html code is added here.When the select box changes according to the result the table is updated
$(document).on('change', '.MemberSelect', function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ memberTypeID: $(".MemberSelect").val() }),
url: "#Url.Action("GetUserMenuDetails", "MenuPermission")",
success: function (data) {
var trHtml = '';
$('#tblClassName tbody').empty();
$.each(data, function (i, item) {
trHtml = trHtml + '<tr><td></td><td>' + (item.LibrarySchooberryMenuDetails!=null? item.LibrarySchooberryMenuDetails.MenuName : "") + '</td>'
'<td>' + item.MenuName + '</td>'
'<td><input type="checkbox" class="MenuMap" id="' + item.MenuID + '" data-id="' + item.MenuID + '"/></td>'
'<td><table>';
$.each(data.LibrarySchooberryMenuFunctions, function (j, functions) {
trHtml = trHtml + '<tr><td><input type="checkbox" class="FunctionMap" id="' + functions.MenuFunctionID + '" data-id="' + functions.MenuFunctionID + '"/>'
+ functions.Name + '<input type="hidden" value="' + functions.MenuID + '" class="menuID" /></td></tr>'
});
trHtml = trHtml + '</table></td></tr>'
});
$('#tblClassName').append(trHtml);
$('#tblClassName').DataTable({
'paging': true,
'lengthChange': false,
'searching': true,
'ordering': true,
'info': true,
'autoWidth': false
});
},
error: function (data) {
}
});
return false;
});
<div class="box-body">
<form id="MenuPermission">
<div class="form-group">
<select class="form-control MemberSelect" name="MemberType"></select>
</div>
<div id="example1_wrapper" class="dataTables_wrapper form-inline dt-bootstrap">
<table class="table table-bordered table-striped" id="tblClassName">
<thead>
<tr>
<th>Sl.NO
</th>
<th>Parent Menu
</th>
<th>Menu
</th>
<th>Is Allowed
</th>
<th>Function</th>
</tr>
</thead>
<tbody>
#{
int i = 1;
foreach (var item in Model)
{
<tr>
<td>#i
</td>
<td>
#Html.DisplayFor(modelItem => item.LibrarySchooberryMenuDetails.MenuName)
</td>
<td>
#Html.DisplayFor(modelItem => item.MenuName)
</td>
<td>
<input type="checkbox" class="MenuMap" id="#item.MenuID" data-id="#item.MenuID"/>
</td>
<td>
<table>
#foreach (var function in item.LibrarySchooberryMenuFunctions)
{
<tr>
<td>
<input type="checkbox" class="FunctionMap" id="#function.MenuFunctionID" data-id="#function.MenuFunctionID"/>
#function.Name
<input type="hidden" value="#function.MenuID" class="menuID" />
</td>
</tr>
}
</table>
</td>
</tr>
}
}
</tbody>
</table>
</div>
</form>
</div>
Refer to my answer here;
How to append ajax result in modal with datatable
First store the initialization to a variable, be sure to put this on the top of the script or inside a $(document).ready(function(){});
var dataTable = $('#tblClassName').DataTable({});
Instead of using jquery append to the table, you have to use the .add() function from the datatable object, then .draw() for refresh;
dataTable.row.Add().draw();
UPDATE:
dataTable.row.add($(trHtml)).draw();
To clear the datatable, use .clear() .
dataTable.clear();
Use this script;
$(document).ready(function(){
var dataTable = $('#tblClassName').DataTable({
'paging': true,
'lengthChange': false,
'searching': true,
'ordering': true,
'info': true,
'autoWidth': false
});
});
$(document).on('change', '.MemberSelect', function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ memberTypeID: $(".MemberSelect").val() }),
url: "#Url.Action("GetUserMenuDetails", "MenuPermission")",
success: function (data) {
var trHtml = '';
// revised //////////////////////
dataTable.clear();
/////////////////////////////////
$.each(data, function (i, item) {
trHtml = trHtml + '<tr><td></td><td>' + (item.LibrarySchooberryMenuDetails!=null? item.LibrarySchooberryMenuDetails.MenuName : "") + '</td>'
'<td>' + item.MenuName + '</td>'
'<td><input type="checkbox" class="MenuMap" id="' + item.MenuID + '" data-id="' + item.MenuID + '"/></td>'
'<td><table>';
$.each(data.LibrarySchooberryMenuFunctions, function (j, functions) {
trHtml = trHtml + '<tr><td><input type="checkbox" class="FunctionMap" id="' + functions.MenuFunctionID + '" data-id="' + functions.MenuFunctionID + '"/>'
+ functions.Name + '<input type="hidden" value="' + functions.MenuID + '" class="menuID" /></td></tr>'
});
trHtml = trHtml + '</table></td></tr>'
});
// revised //////////////////////
dataTable.row.add($(trHtml)).draw();
/////////////////////////////////
},
error: function (data) {
}
});
return false;
});
I have an web api to post data in the table when data entered in html page through jquery.
The web api function is as:
public HttpResponseMessage Post(User user)
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.UserID }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
And the html page with jquery script is:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div>
<h2>All users</h2>
<ul id="users" />
</div>
<div>
<h2>Insert New User</h2>
First Name : <input type="text" id="firstName" /><br />
Last Name : <input type="text" id="lastName" /><br />
City : <input type="text" id="city" /><br />
Email : <input type="email" id="email" /><br />
Password : <input type="password" id="password" /><br />
Phone number: <input type="number" id="phone" /><br />
<input type="button" id="btnsave" value="Save" onclick="Post();" />
<p id="P1" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/user';
$(document).ready(function () {
// Send an AJAX request
getuserlist();
});
function getuserlist() {
$.getJSON(uri)
.done(function (data) {
$('#users').html('');
// On success, 'data' contains a list of users.
$.each(data, function (key, item) {
// Add a list item for the user.
$('<li>', { text: formatItem(item) }).appendTo($('#users'));
});
});
}
function formatItem(item) {
return 'email:' + item.email + ' and First Name:' + item.firstName + ' and Last Name: ' + item.lastName;
}
function Post() {
jQuery.support.cors = true;
var source = {
'firstName': $('#firstName').val(),
'lastName': $('#lastName').val(),
'email': $('#email').val(),
'phone': $('#phone').val(),
'city': $('#city').val(),
'password': $('#password').val()
}
$.ajax({
type: "POST",
dataType: "json",
url: "/api/user",
data: source,
success: function (data) {
var strResult = "<table><th>Returned Message</th>";
// $.each(data, function (index, data) {
strResult += "<tr><td> " + source.email + " </td></tr>"
strResult += "</table>";
$("#divResult").html(strResult);
},
error: function (x, y, z) {
var strResult = "<table><th>Error Message</th>";
// $.each(data, function (index, data) {
strResult += "<tr><td> " + x.responseText + " </td></tr>"
strResult += "</table>";
$("#divResult").html(strResult);
// alert(x + '\n' + y + '\n' + z);
}
//success: function (data) {
// //alert(data);
// getuserlist();
// // alert(jQuery.parseJSON(data));
//},
//error: function (error) {
// jsonValue = jQuery.parseJSON(error.responseText);
// //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
//}
});
});
</script>
</body>
</html>
when I click on the button to add anew user,the post() function is not working.
the page remains the same,no action,no error.
please help!
Thanks!
Firstly the url that you are posting to should be "/api/user/Post".
Output
There are several other JavaScript errors in the posted code that I had to fix. As other's have mentioned in the comments these errors were shown in the console. Knowing how to debug using the developer tools is invaluable and worth investing time to learn them.
Here is the updated code fixed:
<div>
<h2>All users</h2>
<ul id="users" />
</div>
<div>
<h2>Insert New User</h2>
First Name : <input type="text" id="firstName" /><br />
Last Name : <input type="text" id="lastName" /><br />
City : <input type="text" id="city" /><br />
Email : <input type="email" id="email" /><br />
Password : <input type="password" id="password" /><br />
Phone number: <input type="number" id="phone" /><br />
<input type="button" id="btnsave" value="Save" onclick="Post();" />
<p id="P1" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/user';
$(document).ready(function () {
// Send an AJAX request
getuserlist();
});
function getuserlist() {
$.getJSON(uri)
.done(function (data) {
$('#users').html('');
// On success, 'data' contains a list of users.
$.each(data, function (key, item) {
// Add a list item for the user.
$('<li>', { text: formatItem(item) }).appendTo($('#users'));
});
});
}
function formatItem(item) {
return 'email:' + item.email + ' and First Name:' + item.firstName + ' and Last Name: ' + item.lastName;
}
function Post() {
jQuery.support.cors = true;
var source = {
'firstName': $('#firstName').val(),
'lastName': $('#lastName').val(),
'email': $('#email').val(),
'phone': $('#phone').val(),
'city': $('#city').val(),
'password': $('#password').val()
}
$.ajax({
type: "POST",
dataType: "json",
url: "/api/user/Post",
data: source,
success: function (data) {
var strResult = "<table><th>Returned Message</th>";
$.each(data, function (index, data) {
strResult += "<tr><td> " + source.email + " </td></tr>"
strResult += "</table>";
$("#divResult").html(strResult);
});
},
error: function (x, y, z) {
var strResult = "<table><th>Error Message</th>";
$.each(x, function (index, data) {
strResult += "<tr><td> " + x.responseText + " </td></tr>"
strResult += "</table>";
$("#divResult").html(strResult);
// alert(x + '\n' + y + '\n' + z);
});
}
//success: function (data) {
// //alert(data);
// getuserlist();
// // alert(jQuery.parseJSON(data));
//},
//error: function (error) {
// jsonValue = jQuery.parseJSON(error.responseText);
// //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
//}
});
};
</script>
I have also made the assumption that your User object is as follows:
public class User
{
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string city { get; set; }
public string password { get; set; }
}
I'm displaying a list of object data in a table that is triggered by a dropdownbox .change function. However, I also need to submit this data to a database. So far, I can display the data when the dropdown changes, but I'm having trouble retrieving the list of objects and sending them to the database upon submit.
You'll notice that one of the properties in the view model is a boolean. This is used to check which Schools are sent to the database.
The last method shown here is called upon submit. When I check which values are being sent to it (through the tmpModel parameter) the Schools list is null. How can I populate this list with the checked Schools?
First, here is the class from my view model that holds the data I want to display and submit.
public class School
{
public int? SchoolId { get; set; }
public string SchoolName { get; set; }
public string TownName { get; set; }
public bool isMoving { get; set; }
}
Next, here is the JsonResult method I'm using to get the list of Schools.
ReorganizationVm model = new ReorganizationVm(); // an instance of my view model
public JsonResult Schools(int townCode, int sauId, int fiscalYear)
{
using (var service = new ParameterService(this.User))
{
try
{
model.Schools = new List<School>();
foreach (var o in service.GetSchools(townCode, sauId, fiscalYear))
{
School School = new School
{
SchoolId = o.School_ID,
SchoolName = o.SchoolName,
TownName = o.TownName,
isMoving = false
};
model.Schools.Add(School);
}
return Json(model.Schools, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
}
return Json(null);
}
}
Here's JavaScript function that calls the controller method and the table from the view.
<script type="text/javascript">
$(function () {
$('#CurrentSau_SauId').change(function () {
var sauId = $("#CurrentSau_SauId").val();
var townCode = $("#Town_TownCode :selected").val();
var fiscalYear = $("#FiscalYear").val();
var schools = $("#schools");
$.ajax({
cache: false,
type: "GET",
url: "#(Url.Action("Schools", "Reorganization"))",
data: { "sauId" : sauId, "townCode" : townCode, "fiscalYear" : fiscalYear },
success: function (data) {
var result = "";
schools.html('');
$.each(data, function (id, school) {
result += '<tr><th>Select Schools that are Moving to New SAU</th></tr>' +
'<tr><th>School Name</th><th>Town</th><th>Moving to New SU</th></tr>' +
'<tr><td>' + school.SchoolName + '</td><td>' + school.TownName + '</td><td>' +
'<input type="checkbox"></td></tr>';
});
schools.html(result);
},
error: function (xhr, AJAXOptions, thrownError) {
alert('Failed to retrieve schools.');
}
});
});
});
</script>
<table id="schools">
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
And, lastly, the controller method that is called upon submit. Right now, it's empty because I'm only using it to check which values are getting back.
public ActionResult Index(ReorganizationVm tmpModel)
{
return View();
}
Edit: update*
It's been a while but I've finally had some time to come back to this. After trying the code posted by AmanVirdi, I found that it didn't work. However, I was able to get it to work (for the most part) by adding value attributes to the html. Here is the Jquery that builds the html to be injected into the page. Please also note the id variable was changed to i and rather than using html() to inject the html I'm now using append().
JQuery
$.each(data, function (i, school) {
result +=
'<tr><td>' + school.SchoolName +
'<input type="hidden" name="SchoolList[' + i + '].SchoolName" id="SchoolList[' + i + ']_SchoolName" />' +
'<input type="hidden" name="SchoolList[' + i + '].SchoolId" value="' + school.SchoolId + '" /></td>' +
'<td>' + school.Town +
'<input type="hidden" name="SchoolList[' + i + '].Town" value="' + school.Town + '" /></td>' +
'<td><input type="checkbox" name="SchoolList[' + i + '].IsMoving" value="' + school.SchoolId + '" />';
$("#schools").append(result);
As mentioned, it works for the most part. All the values are being sent to the controller except the isMoving checkbox values remain false for each object in the generated list.
How can I get the isMoving values to change according to whether or not the checboxes are checked? I was reading about CheckBoxListFor and think it might help me, but I'm generating the html directly rather than using Html helpers. Maybe I could replicate the html generated by a CheckBoxListFor. Is this the way to go?
you need to add four hidden fields for each property in "Schools" model class, in the "result" string. Like this:
**jQuery:**Tests[position].Test.Preconditions"
result +='<tr><th>Select Schools that are Moving to New SAU</th></tr>' +
'<tr><th>School Name</th><th>Town</th><th>Moving to New SU</th></tr>' +
'<tr><td><input type="hidden" id="SchoolList['+ id +']_SchoolId" name="SchoolList['+ id +'].SchoolId" />' +
'<input type="hidden" id=""SchoolList['+ id +']_SchoolName" name="SchoolList['+ id +'].SchoolName" />'+school.SchoolName + '</td>' +
'<td><input type="hidden" id="SchoolList['+ id +']_TownName" name="SchoolList['+ id +'].TownName" />' + school.TownName +'</td>' +
'<td><input type="checkbox" id="SchoolList['+ id +']_isMoving" name="SchoolList['+ id +'].isMoving" checked="checked"/></td></tr>';
Html
<form action="Controller/Index" method="get">
<!-- <form action="Controller/SaveData" method="get"> for SaveData method -->
<table id="schools">
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
Controller
And add [HttpPost] on the Index method:
[HttpPost]
public ActionResult Index(ReorganizationVm tmpModel)
{
return View();
}
or you can create a separate action method for saving school data.
[HttpPost]
public ActionResult SaveData(ReorganizationVm tmpModel)
{
// do your stuff here
return View("Index");
}
Change your model somthing like this:
public class ReorganizationVm()
{
public List<Schools> SchoolList { get; set; }
}
ReorganizationVm model = new ReorganizationVm(); // an instance of my view model
public JsonResult Schools(int townCode, int sauId, int fiscalYear)
{
using (var service = new ParameterService(this.User))
{
try
{
model.Schools = new List<School>();
foreach (var o in service.GetSchools(townCode, sauId, fiscalYear))
{
School School = new School
{
SchoolId = o.School_ID,
SchoolName = o.SchoolName,
TownName = o.TownName,
isMoving = false
};
model.Schools.Add(School);
}
return Json(model, JsonRequestBehavior.AllowGet); //pass whole model variable
}
catch (Exception ex)
{
}
return Json(null);
}
}
look at this code :
[WebMethod]
public static string GetFacilities(string id)
{
int hotelid = System.Convert.ToInt32(Tools.DecryptString(id));
string ret = "";
foreach (var item in new FacilityGroupBL().Load())
{
if(item.Facilities.Count != 0)
{
ret += "<fieldset>";
if (item.Facilities.Count() != 0)
{
foreach (var subitem in item.Facilities)
{
if (subitem.HotelFacilities.Where(obj => obj.HotelId == hotelid).Count() != 0)
ret += "<input type='checkbox' checked='false' />" + subitem.Name;
else
ret += "<input type='checkbox' checked='true' />" + subitem.Name;
}
}
else
{
ret += "There is no facility in this fieldset.";
ret += "</fieldset>";
}
}
}
return ret;
}
by this code i load some checkboxes in a DIV,then user change some checkboxes and press the SAVE button.at this time ,i should send the values of these checkboxes to server to update my data in database.by i dont know how?:( please help
note: my default code for this probem is here but it does not work($("#FacilitiesDIV input[type=checkbox]").serializeArray() is empty)
$.ajax({
type: "POST",
url: "HotelsList.aspx/SaveFacilities",
data: "{ 'id' : '" + $("#HiddenField").val() + "', 'Facilities' : '" + $("#FacilitiesDIV input[type=checkbox]").serializeArray() + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function () {
$('#dialogMessage').dialog('open');
$('#dialogMessage span').html("Operation Error");
}
});
$("#FacilitiesDIV input[type=checkbox]").serializeArray() since you are referring element using "#" then you need to give the fieldset element an Unique ID assuming you have
html like
<fieldset> <input type='checkbox' checked='false' /> some text
<input type='checkbox' checked='false' /> some text
</fieldset>
set the id to element <fieldset id = 'FacilitiesDIV'>
I believe it should work if you give each checkbox a name, ie:
<input type='checkbox' checked='false' name="mycheckboxes" />