【发布时间】:2018-01-05 21:18:00
【问题描述】:
我进行了调试,发现值正在被传递,但由于某种原因,属性值没有被添加到页面中。我不知道为什么。提交时,将从表单中选择的数据发送到 DisplayProviders。
DisplayProviders 然后将字符串值与提供者机构列表中的属性名称进行比较,然后将找到的数据存储在 TempData 中。发生 RedirectToAction 并将 TempData 发送到 Index()。
视图,在 Index() 的第二次请求之后,然后接收提供者列表。但是,即使 ViewBag 不为空(我在调试中通过了它),当我使用 foreach 浏览它时,它也不会添加代理名称。使用调试,我发现名称正在传递,但 HTML 未添加到页面中。
请帮忙!
在控制器中:
public ActionResult Index()
{
ViewBag.ListOfProviders = TempData["ProvidersFound"];
return View();
}
[HttpGet]
public ActionResult DisplayProviders(string[] area, string[] mode, string[] eligibility)
{
var allProviders = repo.GetProviders();
//Code to narrow down list of providers using the options passed
//through ajax (area, mode, and eligibility) this part works and
//provider agencies were found and stored in TempData
TempData["ProvidersFound"] = providersFound;
return RedirectToAction("Index");
}
查看代码:
@model TransportationProvidersDemo.Models.Provider
@{
var providersFound = ViewBag.ListOfProviders;
}
<--HTML form here (omitted)-->
<input type="submit" />
<div>
@if (providersFound != null)
{
foreach (var item in providersFound)
{
<div>
<h3>@item.AgencyName</h3>
</div>
}
}
</div>
我正在使用 ajax 向 DisplayProviders 发送数据
$.ajax({
type: "GET",
url: "/Home/DisplayProviders",
contentType: "application/json; charset=utf-8",
data: { area: areaSelected, mode: modeSelected, eligibility: eligibilitySelected },
datatype: "json",
traditional: true,
success: function (response) {
if (response != null) {
alert("SUCCESS! Good job!");
} else {
alert("Something went wrong");
}
},
failure: function (response) {
alert("Failure");
},
error: function (response) {
alert("Error");
}
});
【问题讨论】:
-
TempData 存储在会话中,如果我是您,我会避免使用它,因为如果您需要实际扩展,您将被绑定到该服务器。
-
ajax 肯定是在发送数据。问题是 RedirectToAction 是一个客户端重定向,它将数据存储在会话状态中。您不会从 ajax 响应中获得正确的数据
-
你的代码没有意义。 ajax 的全部意义在于保持在 same 页面上并且 ajax 调用从不重定向!无论如何,您永远不会在成功回调中更新 DOM。并且在
DisplayProviders方法中设置TempData不会改变视图中var providersFound的值(它最初是null,不会因为你在服务器上设置而神奇地改变)。您似乎对 ajax 是什么以及它的用途有一个重大误解。
标签: c# ajax asp.net-mvc