我正在尝试将ajax响应数组推入MVC表.这是我的脚本的样子:
$(document).ready(function () {
$('#form1').submit(function (event) {
event.preventDefault();
event.returnValue = false;
var selectValue = $('#selectValue').val();
$.ajax({
url: "/api/Admin/GetDepotDetails/",
type: "POST",
data: { "selectValue": selectValue },
dataType: "json",
success: function (data) {
$("#Grid").html($(data).children());
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
alert(textStatus, errorThrown, jqXHR);
}
});
});
});
这是我的局部视图的样子:
@model IEnumerable
@Html.DisplayNameFor(model => model.DepotID) | @Html.DisplayNameFor(model => model.ColumnName) | @Html.DisplayNameFor(model => model.Country) | @Html.DisplayNameFor(model => model.CountryCode) |
---|
@foreach (var item in Model)
{
@Html.DisplayFor(modelItem => item.DepotID)
@Html.DisplayFor(modelItem => item.ColumnName)
@Html.DisplayFor(modelItem => item.Country)
@Html.DisplayFor(modelItem => item.CountryCode)
}
这就是WebApi方法的样子:
[HttpPost]
public IEnumerable GetDepotDetails(Selected selectValue)
{
var model = depotsDetails.Where(x => x.ColumnName == selectValue.SelectValue) as IEnumerable;
var viewModel = new SearchViewModel{ DepotDetailsList = model, ActionLists = new ActionList()} ;
return model;
}
这就是View的样子:
@model IEnumerable
@*@Html.DropDownListFor(model => model.DepotListSelectValue, Model.DepotLists, new { @class = "form-control" })*@
@Html.DropDownList("selectValue", new List
{
new SelectListItem() {Text = "Depot ID", Value="Depot ID"},
new SelectListItem() {Text = "Depot Name", Value="Depot Name"},
new SelectListItem() {Text = "Address", Value="Address"}
}, new { @class = "selectValue", @id = "selectValue" })
@*//, new { @class = "chzn-select", @id = "chzn-select" }*@
@{
if (Model == null)
{
Html.RenderPartial("_SearchResult", new List() { });
}
}
问题:通过WebApi,我试图获取详细信息列表并将其绑定到MVC表.做这个的最好方式是什么?
我用过
$(“#Grid”).html($(data).children());
填补网格.但该表没有任何数据.有人可以让我知道如何使用上面的部分视图填充网格.
先感谢您!
解决方法:
您的web api端点返回数据(采用json格式),而不是部分视图中的HTML标记.你有2个选择.
1)创建一个mvc动作方法,该方法获取数据并将其传递给局部视图并返回部分视图响应并使用它来更新UI
[HttpPost]
public IEnumerable GetDepotDetails(Selected selectValue)
{
var model = depotsDetails.Where(x => x.ColumnName == selectValue.SelectValue)
as IEnumerable;
return PartialView(model);
}
现在确保在〜/ Views / Shared或〜/ View / YourControllerName /中有一个名为GetDepotDetails.cshtml的局部视图.这个视图应该强烈地输入到DepotDetail的集合中.
@model IEnumerable
Here loop through each item in Model and render the table
Same as your partial view in the question
在你的成功活动中,
success: function (data) {
$("#Grid").html(data);
},
2)使用当前的web api端点并读取ajax方法成功事件中的数据,并动态构建表行的html标记,并将其设置为Grid表的内容.
success: function (data) {
var tblHtml="";
$.each(data.DepotDetailsList,function(a,b){
tblHtml+= "
"+b.DepotID+"";tblHtml+= "
"+b.ColumnName+"";tblHtml+= "
"+b.Country+"";tblHtml+= "
"+b.CountryCode+"M/tr>";});
$("#Grid > tbody").html(tblHtml);
},
标签:jquery,javascript,ajax,asp-net-mvc,asp-net-mvc-4
来源: https://codeday.me/bug/20190623/1270142.html