在 jQuery 中获取多个文本框值 - MVC
Getting Multiple Textboxes Values in jQuery - MVC
我是 MVC 的新手,我正在尝试编辑一行并将编辑后的数据通过 jQuery 和 AJAX 发送到控制器方法,当我单击 edit
特定行变为文本框并且 save
ActionLink 出现而不是 edit
,但是当我保存它时它给了我一个异常,因为 null 将进入 data
jQuery/Ajax代码:
$(document).ready(function () {
function toggleEditability() {
$(this).closest('tr')
.find('a.Edit, a.Save, .displayText, input[type=text]')
}
$('a.Edit').click(toggleEditability);
$('a.Save').click(function () {
toggleEditability.call(this);
var data = $(this).closest('tr').serialize();
alert(data);
//var url = $(this).attr('href');
var actionURL = '@Url.Action("Edit", "Holiday")';
$.ajax({
url: actionURL, // Url to send request to
data:data, // Send the data to the server
type: "POST", // Make it a POST request
dataType: "html", // Expect back HTML
success: function (html) {
$("#dialog-edit").dialog('open');
}
});
});
});
alert(data)
正在显示此
chtml代码:
<div id="details">
<table>
<tr>
@*<th>
@Html.Label("ID")
</th>*@
<th>
@Html.Label("Name")
</th>
<th>
@Html.Label("Description")
</th>
<th>
@Html.Label("Date")
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
if (Convert.ToDateTime(item.Holiday_date).Year.ToString() == DateTime.Now.Year.ToString())
{
<tr>
@* <td>
@Html.TextBoxFor(modelItem => item.Holiday_Id, new { style = "display: none; width:170px; height:15px" })
<div class="displaytext">
@Html.DisplayFor(modelItem => item.Holiday_Id)
</div>
</td>*@
<td>
<div class="HolidayName">
@Html.TextBoxFor(modelItem => item.Holiday_Name, new { id = "", style = "display: none; width:170px; height:15px" })
</div>
<div class="displaytext">
@Html.DisplayFor(modelItem => item.Holiday_Name)
</div>
</td>
<td>
<div class="HolidayDescription">
@Html.TextBoxFor(modelItem => item.Holiday_Description, new { id = "", style = "display: none; width:170px; height:15px" })
</div>
<div class="displaytext">
@Html.DisplayFor(modelItem => item.Holiday_Description)
</div>
</td>
<td>
<div class="HolidayDate">
@Html.TextBoxFor(modelItem => item.Holiday_date, new { id = "", style = "display: none; width:170px; height:15px" })
</div>
<div class="displaytext">
@Html.DisplayFor(modelItem => item.Holiday_date)
</div>
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Holiday_Id }, new { @class = "Edit", Href="#" })
@Html.ActionLink("Save", "Save", new { id = item.Holiday_Id}, new { @class = "Save", Href = "#", style = "display:none" } ) |
@Html.ActionLink("Delete", "Delete", new { id = item.Holiday_Id }, new { @class = "lnkDelete" })
@Html.ActionLink("Cancel", "Cancel", new { id = item.Holiday_Id}, new { @class = "Cancel", Href = "#", style = "display:none" } )
</td>
</tr>
}
}
</table>
</div>
控制器方法代码:
public ActionResult Edit(tbl_HolidayList tbl_holidaylist)
{
if (ModelState.IsValid)
{
db.Entry(tbl_holidaylist).State = EntityState.Modified;
db.SaveChanges();
TempData["Msg"] = "Data has been updated succeessfully";
return RedirectToAction("Index");
}
return PartialView(tbl_holidaylist);
}
tbl_HolidayList.cs
namespace OTESSystem.Models
{
using System;
using System.Collections.Generic;
public partial class tbl_HolidayList
{
public int Holiday_Id { get; set; }
public string Holiday_Name { get; set; }
public string Holiday_Description { get; set; }
public Nullable<System.DateTime> Holiday_date { get; set; }
}
}
你能告诉我如何获取 data
中的文本框值以供 jQuery 保存吗?
方法中出现异常和数据为空:
听起来您的 public ActionResult Edit(tbl_HolidayList tbl_holidaylist)
方法应该接受 JSON 并将其返回。
尝试这样的事情并遍历代码以查看失败的地方:
public JsonResult Edit(tbl_HolidayList model)
{
var hlist = db.tbl_holidaylists.Where(x => x.Id = model.Id).FirstOrDefault();
hlist = model; // something like this to overwrite the existing values...
db.SaveChanges();
return Json(hlist);
}
最后,更改您的 AJAX 成功回调以查看返回的内容:
success: function (html) {
console.log(html);
}
由于序列化不返回任何内容,我建议您获取所需的字段而不是序列化该行。变化
data = $(this).closest('tr').serialize();
在您的 ajax 电话中对此进行
data: {
Holiday_id : $(this).closest('tr').find(".Holiday_id").val(),
Holiday_Name : $(this)...
},
试试这个,首先修改您的视图,为行中需要的字段添加一些标识符。
@Html.TextBoxFor(modelItem => item.Holiday_Id, new { @class = "holidayId"})
@Html.TextBoxFor(modelItem => item.Holiday_Name, new { @class = "holidayName" })
@Html.TextBoxFor(modelItem => item.Holiday_Description, new { @class = "holidayDescription" })
@Html.TextBoxFor(modelItem => item.Holiday_date, new { @class = "holidayDate" })
然后将您的 ajax 通话数据更改为:
var data = {};
data.Holiday_Id = $(this).closest('tr').find(".holidayId").val();
data.Holiday_Name = $(this).closest('tr').find(".holidayName").val();
data.Holiday_Description = $(this).closest('tr').find(".holidayDescription").val();
data.Holiday_Date = $(this).closest('tr').find(".holidayDate").val();
测试警报,如果警报有数据,则在您的控制器操作方法上设置断点并查看参数是否已填写。
你得到 null
for alert(data)
因为你试图序列化最近的 tr
的全部内容并且它也包含 non-input 控件。所以尝试像下面这样只序列化输入控件
var data = $(this).closest('tr').find('input').serialize();
alert(data);
并且您的警报应该 return 您的 tr
数据如下图所示。
如果您的 AJAX 在 Save
操作中发布了模型数据 returns null
,那么另一种方法是从序列化数据对象构建数据数组,并且只拿你需要的东西,比如下面的东西(你的 $('a.Save').click(function () { ...
中的所有下面的代码)
var dataArray = $(this).closest('tr').find('input').serialize();
dataObj = {};
// loop through and create your own data object
$(dataArray).each(function (i, field) {
dataObj[field.name] = field.value;
});
var data = {};
data.Holiday_Id = dataObj['item.Holiday_Id'];
data.Holiday_Name = dataObj['item.Holiday_Name'];
data.Holiday_Description = dataObj['item.Holiday_Description'];
data.Holiday_date = dataObj['item.Holiday_date'];
var actionURL = '@Url.Action("Save", "Holiday")';
$.ajax({
url: actionURL, // Url to send request to
data: JSON.stringify({ model: data }), // Send the data to the server
type: "POST", // Make it a POST request
dataType: "html", // Expect back HTML
contentType: 'application/json; charset=utf-8',
success: function (html) {
$("#dialog-edit").dialog('open');
}
});
现在您应该会在控制器的 Save
操作中看到发布的数据。
更新 1:
根据您评论中指出的错误,您的主键似乎以 null
的形式出现在控制器的操作方法中。您可以将隐藏的输入字段添加到标记中,如下所示。
.....
<td>
@Html.DisplayFor(modelItem => item.Holiday_Id)
@Html.HiddenFor(modelItem => item.Holiday_Id);
</td>
....
Jquery serialize() 不会序列化未设置元素 name
属性的值。请确保您已为所有输入元素指定名称属性。
您还必须在剃刀代码中指定名称属性。
@Html.TextBoxFor(modelItem => item.Holiday_Name,
new { id = "", name="HolidayName",
style = "display: none; width:170px; height:15px" })
根据 JQuery 文档
Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
检查这个 fiddle
您需要在代码中修改的另一件事是以下行。
var data = $(this).closest('tr').find('input').serialize();
因为只有那些具有 name 属性的元素可以被序列化,而您的代码中只有 input 元素。
我是 MVC 的新手,我正在尝试编辑一行并将编辑后的数据通过 jQuery 和 AJAX 发送到控制器方法,当我单击 edit
特定行变为文本框并且 save
ActionLink 出现而不是 edit
,但是当我保存它时它给了我一个异常,因为 null 将进入 data
jQuery/Ajax代码:
$(document).ready(function () {
function toggleEditability() {
$(this).closest('tr')
.find('a.Edit, a.Save, .displayText, input[type=text]')
}
$('a.Edit').click(toggleEditability);
$('a.Save').click(function () {
toggleEditability.call(this);
var data = $(this).closest('tr').serialize();
alert(data);
//var url = $(this).attr('href');
var actionURL = '@Url.Action("Edit", "Holiday")';
$.ajax({
url: actionURL, // Url to send request to
data:data, // Send the data to the server
type: "POST", // Make it a POST request
dataType: "html", // Expect back HTML
success: function (html) {
$("#dialog-edit").dialog('open');
}
});
});
});
alert(data)
正在显示此
chtml代码:
<div id="details">
<table>
<tr>
@*<th>
@Html.Label("ID")
</th>*@
<th>
@Html.Label("Name")
</th>
<th>
@Html.Label("Description")
</th>
<th>
@Html.Label("Date")
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
if (Convert.ToDateTime(item.Holiday_date).Year.ToString() == DateTime.Now.Year.ToString())
{
<tr>
@* <td>
@Html.TextBoxFor(modelItem => item.Holiday_Id, new { style = "display: none; width:170px; height:15px" })
<div class="displaytext">
@Html.DisplayFor(modelItem => item.Holiday_Id)
</div>
</td>*@
<td>
<div class="HolidayName">
@Html.TextBoxFor(modelItem => item.Holiday_Name, new { id = "", style = "display: none; width:170px; height:15px" })
</div>
<div class="displaytext">
@Html.DisplayFor(modelItem => item.Holiday_Name)
</div>
</td>
<td>
<div class="HolidayDescription">
@Html.TextBoxFor(modelItem => item.Holiday_Description, new { id = "", style = "display: none; width:170px; height:15px" })
</div>
<div class="displaytext">
@Html.DisplayFor(modelItem => item.Holiday_Description)
</div>
</td>
<td>
<div class="HolidayDate">
@Html.TextBoxFor(modelItem => item.Holiday_date, new { id = "", style = "display: none; width:170px; height:15px" })
</div>
<div class="displaytext">
@Html.DisplayFor(modelItem => item.Holiday_date)
</div>
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Holiday_Id }, new { @class = "Edit", Href="#" })
@Html.ActionLink("Save", "Save", new { id = item.Holiday_Id}, new { @class = "Save", Href = "#", style = "display:none" } ) |
@Html.ActionLink("Delete", "Delete", new { id = item.Holiday_Id }, new { @class = "lnkDelete" })
@Html.ActionLink("Cancel", "Cancel", new { id = item.Holiday_Id}, new { @class = "Cancel", Href = "#", style = "display:none" } )
</td>
</tr>
}
}
</table>
</div>
控制器方法代码:
public ActionResult Edit(tbl_HolidayList tbl_holidaylist)
{
if (ModelState.IsValid)
{
db.Entry(tbl_holidaylist).State = EntityState.Modified;
db.SaveChanges();
TempData["Msg"] = "Data has been updated succeessfully";
return RedirectToAction("Index");
}
return PartialView(tbl_holidaylist);
}
tbl_HolidayList.cs
namespace OTESSystem.Models
{
using System;
using System.Collections.Generic;
public partial class tbl_HolidayList
{
public int Holiday_Id { get; set; }
public string Holiday_Name { get; set; }
public string Holiday_Description { get; set; }
public Nullable<System.DateTime> Holiday_date { get; set; }
}
}
你能告诉我如何获取 data
中的文本框值以供 jQuery 保存吗?
方法中出现异常和数据为空:
听起来您的 public ActionResult Edit(tbl_HolidayList tbl_holidaylist)
方法应该接受 JSON 并将其返回。
尝试这样的事情并遍历代码以查看失败的地方:
public JsonResult Edit(tbl_HolidayList model)
{
var hlist = db.tbl_holidaylists.Where(x => x.Id = model.Id).FirstOrDefault();
hlist = model; // something like this to overwrite the existing values...
db.SaveChanges();
return Json(hlist);
}
最后,更改您的 AJAX 成功回调以查看返回的内容:
success: function (html) {
console.log(html);
}
由于序列化不返回任何内容,我建议您获取所需的字段而不是序列化该行。变化
data = $(this).closest('tr').serialize();
在您的 ajax 电话中对此进行
data: {
Holiday_id : $(this).closest('tr').find(".Holiday_id").val(),
Holiday_Name : $(this)...
},
试试这个,首先修改您的视图,为行中需要的字段添加一些标识符。
@Html.TextBoxFor(modelItem => item.Holiday_Id, new { @class = "holidayId"})
@Html.TextBoxFor(modelItem => item.Holiday_Name, new { @class = "holidayName" })
@Html.TextBoxFor(modelItem => item.Holiday_Description, new { @class = "holidayDescription" })
@Html.TextBoxFor(modelItem => item.Holiday_date, new { @class = "holidayDate" })
然后将您的 ajax 通话数据更改为:
var data = {};
data.Holiday_Id = $(this).closest('tr').find(".holidayId").val();
data.Holiday_Name = $(this).closest('tr').find(".holidayName").val();
data.Holiday_Description = $(this).closest('tr').find(".holidayDescription").val();
data.Holiday_Date = $(this).closest('tr').find(".holidayDate").val();
测试警报,如果警报有数据,则在您的控制器操作方法上设置断点并查看参数是否已填写。
你得到 null
for alert(data)
因为你试图序列化最近的 tr
的全部内容并且它也包含 non-input 控件。所以尝试像下面这样只序列化输入控件
var data = $(this).closest('tr').find('input').serialize();
alert(data);
并且您的警报应该 return 您的 tr
数据如下图所示。
如果您的 AJAX 在 Save
操作中发布了模型数据 returns null
,那么另一种方法是从序列化数据对象构建数据数组,并且只拿你需要的东西,比如下面的东西(你的 $('a.Save').click(function () { ...
中的所有下面的代码)
var dataArray = $(this).closest('tr').find('input').serialize();
dataObj = {};
// loop through and create your own data object
$(dataArray).each(function (i, field) {
dataObj[field.name] = field.value;
});
var data = {};
data.Holiday_Id = dataObj['item.Holiday_Id'];
data.Holiday_Name = dataObj['item.Holiday_Name'];
data.Holiday_Description = dataObj['item.Holiday_Description'];
data.Holiday_date = dataObj['item.Holiday_date'];
var actionURL = '@Url.Action("Save", "Holiday")';
$.ajax({
url: actionURL, // Url to send request to
data: JSON.stringify({ model: data }), // Send the data to the server
type: "POST", // Make it a POST request
dataType: "html", // Expect back HTML
contentType: 'application/json; charset=utf-8',
success: function (html) {
$("#dialog-edit").dialog('open');
}
});
现在您应该会在控制器的 Save
操作中看到发布的数据。
更新 1:
根据您评论中指出的错误,您的主键似乎以 null
的形式出现在控制器的操作方法中。您可以将隐藏的输入字段添加到标记中,如下所示。
.....
<td>
@Html.DisplayFor(modelItem => item.Holiday_Id)
@Html.HiddenFor(modelItem => item.Holiday_Id);
</td>
....
Jquery serialize() 不会序列化未设置元素 name
属性的值。请确保您已为所有输入元素指定名称属性。
您还必须在剃刀代码中指定名称属性。
@Html.TextBoxFor(modelItem => item.Holiday_Name,
new { id = "", name="HolidayName",
style = "display: none; width:170px; height:15px" })
根据 JQuery 文档
Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
检查这个 fiddle
您需要在代码中修改的另一件事是以下行。
var data = $(this).closest('tr').find('input').serialize();
因为只有那些具有 name 属性的元素可以被序列化,而您的代码中只有 input 元素。