我正在学习ASP.NET MVC 2,我正在尝试做的很简单:
到目前为止,一切正常,但我的View未更新,并且未显示特定产品类型的产品列表。
我想也许是因为[HTTPPost]
只是发布到视图模型并且它实际上没有更新视图?
有关如何根据下拉选项更新视图的任何建议?
型号:
公共类供应商模型 { 公共供应商模型() { }
public SuppliersModel(string type)
{
ProductsByType = Products.Where(i => i.Type == type);
}
public IEnumerable<Products> ProductsByType { get; set; }
public List<Products> Products
{
get
{
List<Products> mockProducts = new List<Products>()
{
new Products{Type="Fruit", Name="Apple"},
new Products{Type="Fruit", Name="Orange"},
new Products{Type="Vegetables", Name="Potato"},
new Products{Type="Vegetables", Name="Carrot"}
};
return mockProducts;
}
}
public SelectList ProductTypes
{
get { return GetProductTypes(); }
}
private SelectList GetProductTypes()
{
var productTypes = new List<SelectListItem>
{
new SelectListItem{ Value="Fruit",Text="Fruit"},
new SelectListItem{ Value="Vegetables",Text="Vegetables"}
};
var list = new SelectList(productTypes, "Value", "Text");
return list;
}
}
公共类产品 { public string Type {get;组; } public string Name {get;组; } }
查看:
<script type="text/javascript">
$(function () {
$('#products').change(function () {
$.post('<%=Url.Action("GetProductsByType", "Suppliers")%>', { type: $(this).val() },
function (result) {
});
});
});
</script>
<h2>
Suppliers</h2>
<%= Html.DropDownList("products",Model.ProductTypes) %>
<table>
<% if (Model.ProductsByType != null) foreach (var item in Model.ProductsByType)
{ %>
<tr>
<td>
<%= item.Name %>
</td>
<td>
<%= item.Type %>
</td>
</tr>
<% } %>
</table>
控制器:
public class SuppliersController : Controller
{
public ActionResult Suppliers()
{
SuppliersModel model = new SuppliersModel();
return View(model);
}
[HttpPost]
public ActionResult GetProductsByType(string type)
{
//This executes when the value in the drop down changes
SuppliersModel model = new SuppliersModel(type);
return View(model);
}
}
答案 0 :(得分:0)
看起来你没有对你的控制器在帖子之后返回的html做任何事情,
<script type="text/javascript">
$(function () {
$('#products').change(function () {
$.post('<%=Url.Action("GetProductsByType", "Suppliers")%>', { type: $(this).val() },
function (result) {
//result will have the html that your controller returns after the post
// you can do something like,
$('#some-div').html(result);
});
});
});
</script>