【发布时间】:2015-11-30 05:59:00
【问题描述】:
注意:我是 MVC 新手
在我的情况下,它有两个视图和两个控制器。我使用 ajax 从第一个视图将选定的项目值传递给第二个控制器。传递是成功的。 但是当第二个视图出现时,值为null。这是ajax问题还是mvc。看不懂。
这是我的第一个控制器和第一个视图
public ActionResult First()
{
//get the location data
var Loc = getData("Location", "", "", "");
List<Firstdata> llc = new List<Firstdata>();
foreach (var val in Loc)
{
llc.Add(new Firstdata
{
Destination =val
});
}
ViewBag.Loc = llc;
return View();
}
第一次查看
<div class="col-md-6 form-group">
<label>Destination</label>
<select class="form-control" id="destination">
@foreach (var item1 in @ViewBag.Loc)
{
<option>@item1.Destination</option>
}
</select>
</div>
<div class="clearfix"></div>
<div class="form-group">
<div class="btn" id="bud">
@Html.ActionLink("GO", "Check","Cruise")
</div>
</div>
ajax 在第一个视图中传递
<script type="text/javascript">
$("#bud a").click(function () {
var destination = $("#destination").val();
$.ajax({
url: '@Url.Action("Check","Cruise")',
data: { 'destination': destination },
type: "POST",
dataType: "XML",
//contentType: "application/xml",
async: true,
success: function(data){
if (!data)
alert("no xml data returned");
else {
alert("success");
}
//location.href = "~/Views/Cruise/Check.cshtm";
}
});
});
</script>
这是我的第二个控制器
public ActionResult Check(string destination)
{
XElement rootele = XElement.Load(Server.MapPath("~/XmlFiles/CruiseData/cruiseprodutstwo.xml"));
var getneededData = rootele.Elements("CruiseProduct")
.Where(l => l.Element("Location").Value == destination)
.Select(s => s.Element("Name").Value);
List<Details> d = new List<Details>();
foreach(var itm in getneededData)
{
d.Add(new Details
{
cruiseName = itm
});
}
ViewBag.needed = d;
return View();
}
** 在这一点上,destination 不为 null,d(ViewBag.needed) 也不为 null。它显示了计数
这是我的第二个观点
<div>
@foreach (var itme in @ViewBag.needed)
{
<h2>@itme</h2>
}
</div>
在这里循环遍历@ViewBag.needed count,最后显示null。不知道发生了什么。 请帮帮我。
【问题讨论】:
-
if(d.Count > 0)然后循环。它会告诉你d是否有任何数据。你调试了吗?您还可以回退以查看数据,例如(List<Details>)@ViewBag.needed。还要检查您的string destination是否有值? -
我似乎对这里使用 ajax 感到困惑。似乎您正在提供一个操作链接,并且仍在使用 ajax 来生成单击事件。尝试不使用 ajax 的动作点击。
-
它不能用来发送选择项
标签: c# jquery ajax model-view-controller