我从前几天开始使用web grid。一切都是如此方便的webgrid,如显示不同数据类型的列,如文本框,标签,下拉列表等。但我如何保存数据或更新数据。
我尝试使用操作链接和提交按钮,但它们都不起作用。他们没有在我的控制器中获取修改后的下拉数据。操作链接能够获取用户id,但它无法获取更改后的下拉值。
代码如下:
视图
WebGridColumn colLocation = null;
foreach (var col in Model)
{
colLocation = new WebGridColumn()
{
Header = "Locations",
Format = (item) => @Html.DropDownList("LocationId", @col.LocationItems.Select(l => new SelectListItem
{
Text = l.Text,
Value = l.Value,
Selected = ((WebGridRow)item)["LocationId"].ToString() == l.Value
}
)
)
};
colSave = new WebGridColumn()
{
Header = "Save User",
Format = (item) => Html.ActionLink("Save", "Save", "UsersList", new { userId = item.UserId, locationId = item.LocationId }, new { @class = "btn btn-default" }),
CanSort = true
};
}
columns.Add(colLocation);
columns.Add(colSave);
@grid.GetHtml(tableStyle: "webgrid",
headerStyle: "header",
selectedRowStyle: "select",
alternatingRowStyle: "alt",
columns: columns
)控制器
public ActionResult Save(int userId, int locationId)
{
var user = Utility.SetUserDetails(userId, locationId);
return RedirectToAction("UsersList");
}发布于 2017-09-07 22:39:05
经过一些严格的测试,我已经实现了这个功能。这可以使用ajax来完成。
我必须扩展我的列属性以包含class & id属性
colUser = new WebGridColumn()
{
Header = "User Id",
ColumnName = "UserId",
CanSort = true,
Format = @<text>
<span class="display"><label id="lblUserId">@item.UserId</label></span>
<input type="text" id="inUserId" value="@item.UserId" class="edit" style="visibility:hidden" />
</text>
};
colLocation = new WebGridColumn()
{
Header = "Locations",
Format = @<text>
@Html.DropDownList("Location", @col.LocationItems.Select(l => new SelectListItem
{
Text = l.Text,
Value = l.Value,
Selected = ((WebGridRow)item)["LocationId"].ToString() == l.Value
}
), new { @class = "edit", @id = "inLocation" })
</text>
};
colSave = new WebGridColumn()
{
Header = "Save User",
Format = @<text>
<a href="#" class="edit save-btn btn btn-default">Save</a>
</text>
};添加jquery脚本后,我们可以将选定的值发布到控制器中。
<script type="text/javascript">
$(function () {
$('.save-btn').on("click", function () {
var tr = $(this).parents('tr:first');
var id = tr.find("#inUserId").val();
var location = tr.find("#inLocation").val();
var User =
{
"UserId": id,
"LocationId": location
};
$.ajax({
url: '/UsersList/SaveData/',
data: JSON.stringify(User),
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
isSuccess = result;
},
error: function (result) {
isSuccess = result;
}
})
});
});
</script>在控制器中,添加新方法,
public ActionResult SaveData(UserAccountViewModel User)
{
int userId = User.UserId;
int locationId = Convert.ToInt32(User.LocationId);
var user = Utility.SetUserDetails(userId, locationId);
return RedirectToAction("UsersList");
}https://stackoverflow.com/questions/46094294
复制相似问题