从 Html 表中获取值并使用 jQuery 映射到 C# 列表



我有一个MVC项目,我在我的部分视图中使用表格将数据呈现为:

<table id="tblUserSettings" class="table table-bordered CmtTable">
<thead>
<tr>
<th>User Name</th>
<th>Country</th>
<th>System (s)</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@if (Model == null)
{
<tr></tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td><input type="hidden" id="usrId" value="@item.UserId" />
@item.UserName</td>
<td> <input type="hidden" id="usrCountryKey" value="@item.UserCountryKey" style="display:none"/>
@item.UserCountryName</td>
<td> <input type="hidden" id="usrSourceSystemKey" value="@item.UserSourceSystemKey" />
@item.UserSourceSystemDescription</td>
<td><a onclick='DeleteUserSettingsRow();'><i class='fa fa-times'></i> Delete</a><a onclick='EditUserSettingsPopup();'><i class='fa fa-pencil'></i> Edit</a></td>
</tr>
}
}
</tbody>
</table>

我要将此表中的值保存到数据库中,并且需要在控制器中调用 AddUserSettingsaction 方法,如下所示:

[HttpPost, Route("AddUserSettings")]
public ActionResult AddUserSettings(IEnumerable<UserSettings> request)
{
AddUserSettingsRequest apiRequest = null;
return View();
}

用户设置的模型如下:

public class UserSettings
{
public UserSettings();
public string UserId { get; set; }
public string UserName { get; set; }
public string UserCountryKey { get; set; }
public string UserCountryName { get; set; }
public string UserSourceSystemKey { get; set; }
public string UserSourceSystemDescription { get; set; }
}

我需要使用 jQuery 将表中的数据(包括隐藏字段(保存到数据库中,因此我创建了一个函数并将其调用为:

<button type="button" id="btnAdd" onclick="SaveUserSettings();"><i class="fa fa-save"></i> Save</button>
function SaveUserSettings()
{
debugger;
var userSettings = [];
$("table#tblUserSettings tr").each(function (i, v) {
userSettings[i] = [];
$(this).children('td').each(function (ii, vv)
{
userSettings[i][ii] = $(this).text();
});
})
alert(userSettings);
$.ajax({
url: '@Url.Action("AddUserSettings", "Admin")',
type: "POST",
contentType: "application/json;",
data: JSON.stringify(userSettings),
success : function (result)
{
//alert(result);
},
error: function (result)
{
//alert(result);
}
});
}

使用上面的 SaveUserSettings(( 函数,我可以获取未隐藏的值,但我需要创建一个数组,该数组也包含隐藏属性,并且可以与 ajax 请求一起作为参数发送到控制器。如何获取隐藏字段并创建一个映射到控制器的 IEnumerable 请求的数组?

如果 javascript 位于分部视图中,您可以直接针对模型设置 userSettings,例如:

var userSettings = @Html.Raw(JsonConvert.SerializeObject(Model));

然后,这会将您的对象序列化为 JSON,并将其传递给浏览器,然后您可以使用它将其传递回 jQuery 中的服务器,而无需遍历表中的每一行。

最新更新