我正在尝试更新html表,然后使用ajax和jquery将其更改提交给控制器。目前我能够填充并对表进行更改,但是当我将其提交给控制器时,没有进行任何更改。即使已从UI进行了更改,集合中的复选框也始终为false。我一直在尝试一些方法,所以代码可能有点乱。
下面的Create.cshtml:
@model POS.BusinessLayer.Models.userRoleURF
@{
ViewBag.Title = "Create";
}
<h2>View</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>userRoleFeature</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.userRoleFeature.urfCompanyId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.companyDropDown.CompanyId, Model.companyDropDown.data, "--Select Company--", new { @class = "form-control", id = "CompanyId" })
@*@Html.EditorFor(model => model.urfCompanyId, new { htmlAttributes = new { @class = "form-control" } })*@
@Html.ValidationMessageFor(model => model.userRoleFeature.urfCompanyId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.userRoleFeature.urfRoleId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.userRoleDropDown.RoleId, Model.userRoleDropDown.data, "--Select Role--", new { @class = "form-control", id = "RoleId" })
@*@Html.EditorFor(model => model.urfRoleId, new { htmlAttributes = new { @class = "form-control" } })*@
@Html.ValidationMessageFor(model => model.userRoleFeature.urfRoleId, "", new { @class = "text-danger" })
<div id="loadingRoles" style="display: none;">
<img src="~/Content/Images/ajax-loader.gif" alt="Loading..." />
</div>
</div>
</div>
<table class="table" id="featureTable">
<tr>
<th>
@Html.DisplayNameFor(model => model.urfResults.First().userFtrDescription)
</th>
<th>
@Html.DisplayNameFor(model => model.urfResults.First().urfEnabled)
</th>
</tr>
@*foreach (var item in Model.urfResults)*@
@for (int i = 0; i < Model.urfResults.Count(); i++)
{
<tr id="featureRow">
<td>
@Html.DisplayFor(x => x.urfResults[i].userFtrDescription)
@*@Html.DisplayNameFor(modelItem => modelItem.urfResults[i].userFtrDescription)*@
</td>
<td>
<div class="checkbox">
@Html.CheckBoxFor(x => x.urfResults[i].urfEnabled)
@*@Html.EditorFor(modelItem => modelItem.urfResults[i].urfEnabled)*@
</div>
</td>
</tr>
}
</table>
<div id="loadingFeatures" style="display: none;">
<img src="~/Content/Images/ajax-loader.gif" alt="Loading..." />
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input id="mysubmitbutton" type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@Scripts.Render("~/Scripts/userRoleFeatureIndex.js")
下面的JavaScript代码:
$(function () {
$("#mysubmitbutton").submit(function(){
var tblFeature = $("#featureTable");
// If selected roleID is not null
var CompanyID = parseInt($("#CompanyId").val());
var RoleID = parseInt($("#RoleId").val());
var array = [];
$('#featureTable > tbody > tr').each(function (elem) {
var item = {};
item.userFtrDescription = $(this).find("td > #urfResult_" + elem + "_userFtrDescription").val();
item.urfEnabled = $(this).find("td > #urfResult_" + elem + "_urfEnabled").val();
array.push(item);
});
var data = JSON.stringify(array);
$.ajax({
url: "/userRoleFeature/CreateURF/",
type: "POST",
data: { selectedCompanyId: CompanyID, selectedRoleId: RoleID, featureList: tblFeature},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
}
});
});
$("#CompanyId").change(function () {
// this will call when Country Dropdown select change
var CompanyID = parseInt($("#CompanyId").val());
if (!isNaN(CompanyID)) {
var ddRole = $("#RoleId");
ddRole.empty(); // this line is for clear all items from role dropdown
ddRole.append($("<option></option").val("").html("Select Role"));
// Here I will call Controller Action via Jquery to load role for selected company
$("#loadingRoles").show();
$.ajax({
url: "/userRoleFeature/roleList",
//url: "@Url.Action('roleList','userRoleFeature')",
type: "POST",
data: { selectedCompanyId: CompanyID },
dataType: "json",
success: function (roles) {
$("#loadingRoles").hide();
$.each(roles, function (i, roles) {
//ddRole.append($("<option></option>").val(val.Value).html(val.Text));
ddRole.append("<option value='" + roles.Value + "'>" + roles.Text + "</option>");
});
},
error: function (request, status, error) {
$("#loadingRoles").hide();
alert(request.responseText);;
}
}); // End of Ajax Call
} // End if Company Id is selected
}); //End Company Change Function
//start if roleId changes
$("#RoleId").change(function () {
// If selected roleID is not null
var CompanyID = parseInt($("#CompanyId").val());
var RoleID = parseInt($("#RoleId").val());
if (!isNaN(RoleID)) {
var tblFeature = $("#featureTable");
//$("#featureTable tbody tr").remove();
tblFeature.find("tr:gt(0)").remove();
// Here I will call Controller Action via Jquery to load features for selected role
$("#loadingFeatures").show();
$.ajax({
url: "/userRoleFeature/urfList",
//url: "@Url.Action('urfList','userRoleFeature')",
type: "POST",
data: { selectedCompanyId: CompanyID, selectedRoleId: RoleID },
dataType: "json",
success: function (urfResults) {
$("#loadingFeatures").hide();
var trHTML = "";
$.each(urfResults, function (i, item) {
//ddRole.append($("<option></option>").val(val.Value).html(val.Text));
trHTML += "<tr>";
//trHTML += "<td>" + item.userFtrDescription + "</td>";
//trHTML += '<td><input id= "urfResult_' + i + ' _userFtrDescription" name= "urfResults[' + i + ' ].userFtrDescription" type="Text" value="' + item.userFtrDescription + '" style="border:none; width:100%" /></td>'
//trHTML += "<td><input id= 'urfResult_" + i + "_userFtrDescription' name= 'urfResults[" + i + "].userFtrDescription' type='Text' readonly value='" + item.userFtrDescription + "' style='border:none; width:100%' /><input name= 'urfResults[" + i + "].userFtrDescription' type='hidden' value= '" + item.userFtrDescription + "' /></td>";
//trHTML += "<td><input name= urfResults['" + i + "'].urfEnabled type='checkbox' value='" + item.urfEnabled + "'/> <input name= urfResults['" + i + "'].urfEnabled type='checkbox' value='" + item.urfEnabled + "'/></td>";
//trHTML += "</tr>";
trHTML += "<td><input id= 'urfResult_" + i + "_userFtrDescription' name= 'urfResults[" + i + "].userFtrDescription' type='Text' readonly value='" + item.userFtrDescription + "' style='border:none; width:100%' /></td>";
trHTML += "<td><input id='urfResult_" + i + "_urfEnabled' name= urfResults['" + i + "'].urfEnabled type='checkbox' value='" + item.urfEnabled + "'/> </td>";
trHTML += "</tr>";
});
tblFeature.append(trHTML);
},
error: function (request, status, error) {
$("#loadingRoles").hide();
alert(request.responseText);
}
}); // End of Ajax Call
} // End if selected role is not null
}); //If roleId changes
});
控制器代码如下:
[HttpPost]
public ActionResult Create(userRoleURF collection)
{
try
{
// TODO: Add insert logic here
var blURF = new blUserRoleFeature();
var myURF = collection.urfResults;
var myCompany = collection.companyDropDown.CompanyId;
var myRole = collection.userRoleDropDown.RoleId;
foreach(var item in myURF)
{
var iURF = new userRoleFeature()
{
urfCompanyId = myCompany,
urfEnabled = item.urfEnabled,
urfRoleId = myRole,
urfId = 0,
urfCreatedBy = 0,
urfCreatedOn = Convert.ToDateTime("01/01/1978"),
urfModifiedBy = 0,
urfModifiedOn = Convert.ToDateTime("01/01/1978")
};
//var result = blURF.urfCreate(iURF);
}
return RedirectToAction("Index");
}
catch(Exception ex)
{
Response.Write(ex.Message);
return View();
}
}
Model details below:
public class userRoleURF
{
public userRoleDropDown userRoleDropDown { get; set; }
public IList<userRoleFeatureG> urfResults { get; set; }
public userRoleFeature userRoleFeature { get; set; }
public companyDropDown companyDropDown { get; set; }
}
public class userRoleFeatureG
{
//public int userFtrId { get; set; }
[DisplayName("Feature Description")]
public string userFtrDescription { get; set; }
[DisplayName("Enabled")]
public bool urfEnabled { get; set; }
}
答案 0 :(得分:0)
我找到了解决办法:删除标准的beginform并使用click事件上的submit按钮来调用Jquery函数。它找到所有选中的框并将它们放入一个数组中。然后它调用一个JsonResult控制器,该控制器获取所有选中的框并对其进行操作:
更新了Jquery代码:
$(function(){
var chkItems = new Array();
$('#mysubmitbutton').click(function () {
var CompanyID = parseInt($('#CompanyId').val());
var RoleID = parseInt($('#RoleId').val());
$('#featureTable tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked')) {
var id = row.find('[type="checkbox"]').attr("value");
chkItems.push(id);
}
});
$.ajax({
type: 'POST',
url: '/userRoleFeature/submitURF',
data: { id: chkItems, selectedCompanyId: CompanyID, selectedRoleId: RoleID },
//contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data) {
//$('#spanResults').text(data.join(','));
window.location.href = '/Home/Index';
},
error: function(e) {
alert(e.message);
}
});
});
$("#CompanyId").change(function () {
// this will call when Country Dropdown select change
var CompanyID = parseInt($("#CompanyId").val());
if (!isNaN(CompanyID)) {
var ddRole = $("#RoleId");
ddRole.empty(); // this line is for clear all items from role dropdown
ddRole.append($("<option></option").val("").html("Select Role"));
// Here I will call Controller Action via Jquery to load role for selected company
$("#loadingRoles").show();
$.ajax({
url: "/userRoleFeature/roleList",
//url: "@Url.Action('roleList','userRoleFeature')",
type: "POST",
data: { selectedCompanyId: CompanyID },
dataType: "json",
success: function (roles) {
$("#loadingRoles").hide();
$.each(roles, function (i, roles) {
//ddRole.append($("<option></option>").val(val.Value).html(val.Text));
ddRole.append("<option value='" + roles.Value + "'>" + roles.Text + "</option>");
});
},
error: function (request, status, error) {
$("#loadingRoles").hide();
alert(request.responseText);;
}
}); // End of Ajax Call
} // End if Company Id is selected
}); //End Company Change Function
//如果roleId发生变化,则启动 $(&#34;#RoleId&#34;)。change(function(){
// If selected roleID is not null
var CompanyID = parseInt($("#CompanyId").val());
var RoleID = parseInt($("#RoleId").val());
if (!isNaN(RoleID)) {
var tblFeature = $("#featureTable");
//$("#featureTable tbody tr").remove();
tblFeature.find("tr:gt(0)").remove();
// Here I will call Controller Action via Jquery to load features for selected role
$("#loadingFeatures").show();
$.ajax({
url: "/userRoleFeature/urfList",
//url: "@Url.Action('urfList','userRoleFeature')",
type: "POST",
data: { selectedCompanyId: CompanyID, selectedRoleId: RoleID },
dataType: "json",
success: function (urfResults) {
$("#loadingFeatures").hide();
var trHTML = "";
$.each(urfResults, function (i, item) {
trHTML += "<tr>";
trHTML += "<td><input id= 'urfResult_" + i + "__userFtrDescription' name= 'urfResults[" + i + "].userFtrDescription' type='Text' value='" + item.userFtrDescription + "' style='border:none; width:100%' /></td>";
if (item.urfEnabled == true)
{
trHTML += "<td><input class='check-box' id='urfResult_" + i + "__urfEnabled' name= urfResults[" + i + "].urfEnabled type='checkbox' checked='true' value='" + item.userFtrId + "' /><input name= urfResults[" + i + "].urfEnabled type='hidden' value='false' /></td>";
} else {
trHTML += "<td><input class='check-box' id='urfResult_" + i + "__urfEnabled' name= urfResults[" + i + "].urfEnabled type='checkbox' value='" + item.userFtrId + "' /><input name= urfResults[" + i + "].urfEnabled type='hidden' value='false' /></td>";
}
trHTML += "</tr>";
});
tblFeature.append(trHTML);
},
error: function (request, status, error) {
$("#loadingRoles").hide();
alert(request.responseText);
}
}); // End of Ajax Call
} //如果所选角色不为空,则结束
}); //如果roleId更改
});
更新了控制器代码:
public JsonResult submitURF(List<string> id, int selectedCompanyId, int SelectedRoleId)
{
var blURF = new blUserRoleFeature();
var deleteResult = blURF.urfDelete(SelectedRoleId);
foreach (var item in id)
{
var iURF = new userRoleFeature()
{
urfCompanyId = selectedCompanyId,
urfRoleId = SelectedRoleId,
urfEnabled = true,
urfFeatureId = Convert.ToInt16(item)
};
var result = blURF.urfCreate(iURF);
}
return Json(id);
}e: