【发布时间】:2019-03-03 00:57:04
【问题描述】:
控制器
public ActionResult ImportListByVesselVoyage()
{
return View();
}
[HttpPost]
public ActionResult ImportListByVesselVoyage(WebTrackParam param)
{
client = new HttpClient();
List<ImportListByVesselVoyageGetILBV> appMenu = new List<ImportListByVesselVoyageGetILBV>();
client.BaseAddress = new Uri(url);
MediaTypeWithQualityHeaderValue contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
try
{
HttpResponseMessage response = client.GetAsync(string.Format("/Services/WebTrack.svc/ImportListByVesselVoyageGetILBVJSONData/{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}/{8}/{9}/{10}", "VR", "2018", param.reg, " ", " ", "A", "A", "S,Y,D", "F,L,E,T", "ITTEST", "2")).Result;
if (response.IsSuccessStatusCode)
{
var stringData = response.Content.ReadAsStringAsync().Result;
JObject result = JObject.Parse(stringData);
var appMenuarray = result["ImportListByVesselVoyageGetILBVResult"].Value<JArray>();
appMenu = appMenuarray.ToObject<List<ImportListByVesselVoyageGetILBV>>();
ViewBag.ILBV = appMenu;
}
return View();
}
catch (Exception ex)
{
return PartialView("ImportListByVesselVoyage", appMenu);
}
finally
{
client.Dispose();
client = null;
}
}
查看
@model List<WebTrack.Models.ImportListByVesselVoyageGetILBV>
@using (Html.BeginForm("ImportListByVesselVoyage", "Containerized", FormMethod.Post))
{
<div class="box-body">
<div class="form-group">
<div class="col-sm-6">
@Html.TextBoxFor(model => model.reg)
</div>
</div>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-info pull-right"><i class="fa fa-search"></i>Search</button>
</div>
<div id="result">
<div class="col-md-12">
<div class="box">
<div class="box-body no-padding">
<table class="table table-striped">
<tbody>
<tr>
<th>Container No.</th>
<th>Operator</th>
<th>Status</th>
<th>Size</th>
<th>Commodity</th>
<th>Destination</th>
<th>Location</th>
<th>Discharged</th>
<th>Delivered</th>
</tr>
@foreach (var item in ViewBag.ILBV)
{
<tr>
<td>@item.ContainerNo</td>
<td>@item.Operator</td>
<td>@item.Status</td>
<td>@item.Size</td>
<td>@item.Commodity</td>
<td>@item.Destination</td>
<td>@item.Location</td>
<td>@item.Discharged</td>
<td>@item.Delivered</td>
</tr>
}
</tbody>
</table>
</div>
<div class="box-footer clearfix">
<ul class="pagination pagination-sm no-margin pull-right"></ul>
</div>
</div>
</div>
</div>
}
我将从@Html.TextBox() 获取“reg”并将其传递给[HttpPost] 公共 ActionResult ImportListByVesselVoyage(WebTrackParam 参数)。 我想知道如何将结果 appMenu 返回到我的视图。而且我尝试使用 ViewBag.ILBV 但由于它在 HttpPost 上,它会在 Get 期间导致 null 错误。
谢谢,希望你能理解我的担心。我是 MVC 新手。
【问题讨论】:
-
您是否在视图顶部正确提及了@model?
-
是的,我有。我的主要问题是当我从 HttpPost 使用 ViewBag 时出现 null 错误,因为它在 get 方法中没有任何值。
-
Viewbag 不用于往返。您只能通过控制器发送数据以在 viewbag 中查看。如果您希望数据出现在下一个请求中,请使用会话
-
不要使用
ViewBag。在方法中创建一个List<ImportListByVesselVoyageGetILBV>并将其返回给视图并使用@foreach (var item in Model)(在GET 方法中只需使用return View(new List<ImportListByVesselVoyageGetILBV>());返回一个空集合
标签: asp.net-mvc