【发布时间】:2013-03-05 09:18:10
【问题描述】:
我是一名桌面开发人员,我正在使用 C# 自学 ASP.NET MVC3(还不能使用 MVC4...)。出于这个原因,我将一些小的虚拟项目放在一起。在这个项目中,我使用带有电影类别的 DropDownListFor(我们都知道这个例子对吧?)。但是因为本教程的速度太快了,所以我正在尝试做一些更简单的事情。
我的模特:
public class MovieModel {
public int SelectedCategorieID { get; set; }
public List<CategorieModel> Categories { get; set; }
public MovieModel() {
this.SelectedCategorieID = 0;
this.Categories = new List<CategorieModel>() {new CategorieModel {ID = 1,
Name = "Drama"},
new CategorieModel {ID = 2,
Name = "Scifi"}};
}
}
public class CategorieModel {
public int ID { get; set; }
public string Name { get; set; }
}
看到了吗?很简单。我有一个强类型视图,我可以在其中使用这个模型:
@model MvcDropDownList.Models.MovieModel (1st line of Index.cshtml).
模型在调用 Home 控制器的默认动作时被填充:
public ActionResult Index() {
ViewBag.Message = "Welcome to ASP.NET MVC!";
Models.MovieModel mm = new Models.MovieModel();
return View(mm);
}
到目前为止一切顺利。没问题。现在我想用不显眼的 ajax 在部分视图中向用户显示它选择的类别的 ID……因为我没有让它工作,所以我开始的时候更小了。现在忘记DrowpdownList。我现在只有这个按钮:
<input type="button" value="Minicart test" onclick="categoryChosen();" />
还有这个 div:
<div id="minicart">
@Html.Partial("Information")
</div>
迷你购物车的东西来自另一个教程,我很抱歉。请不要让它分散你的注意力。
这个javascript:
function categoryChosen() {
var url = "Home/CategoryChosen/" + "2";
$.post(url, function (data) {
debugger;
$("#miniCart").html(data);
});
}
2 确实是可靠的,从我之前的尝试让它工作。最终我当然希望它是可变的......
调用此操作:
[AcceptVerbs("POST")]
public ActionResult CategoryChosen(string SelectedCategorieID) {
ViewBag.messageString = "2";
return PartialView("Information");
}
是的,你没看错。我只是插入 2 进行测试。因为就像我说的,不能让它工作。部分视图信息如下所示:
@{
ViewBag.Title = "Information";
}
<h2>Information</h2>
<h2>You selected: @ViewBag.messageString</h2>
那么,现在是一个大问题。我希望部分视图呈现:“您选择:2”。我什至在调试 javascript 并查看变量“数据”中的内容时看到了这一点。谁能帮我为什么它不渲染2?然后我可以继续自学这些东西。非常感谢您的帮助。如果您错过任何类型的信息,请随时询问。
【问题讨论】:
-
我会使用集成的 MVC-Ajax 功能。看看 Ajax.Beginform 和 unobtrusive ajax。我喜欢这个教程asp.net/mvc/tutorials/older-versions/javascript/…