我想在MVC 5中有下拉列表,我想知道用户选择了哪个项目。 我正在搜索并找到以下解决方案,但在Http.DropDownList中的View代码错误
new{id ="dropdownlist1"}
我的代码是:
在我的控制器中我有:
public ViewResult ExistHW()
{
#region
List<SelectListItem> HWType = new List<SelectListItem>();
HWType.Add(new SelectListItem { Text = "Monitor ", Value = "Monitor" });
HWType.Add(new SelectListItem { Text = "Case", Value = "Case" });
.....
#endregion
ViewBag.HWType = HWType;
return View(); }
我是我的观点:
@Html.DropDownList("HWType", "-- select ---",new{ id = "dropdownlist1"} )
$('#dropdownlist1').change(function () {
jQuery.getJSON('@Url.Action("SelectType")', { id: $(this).attr('value') }, function(data) { });
那在我的控制者中:
public ActionResult SelectType(String value)
{
switch (value)
{case "Monitor":
break;
case "Case":
break;
....
}
return View();
}
答案 0 :(得分:0)
在致电getJSON
时,您将id
参数传递给SelectType
。但是,根据操作方法的签名,参数应命名为value
将getJSON
来电更改为:
jQuery.getJSON('@Url.Action("SelectType")',
{ value: $(this).attr('value') },
function(data) { });
答案 1 :(得分:0)
如果您想根据DropDownList中的选定项目更改部分页面,可以使用以下示例并根据您的情况进行更新:
<script type="text/javascript">
$(document).ready(function () {
submitform = function (flag) {
var ProductCatID = $("#ProductCategoryId").val();
var param = { ProdCatID: ProductCatID, Flag: flag };
var ul = '@Url.Action("GetProdPropertyValues", "ManageProducts")';
$.ajax({
url: ul + "?ProdCatID=" + ProductCatID + "&&Flag=" + flag,
type: 'GET',
async: true,
success: function (result) {
if (result != "") {
$("#partialView").empty();
$("#partialView").html(result);
}
},
error: function (xhr, status, error) {
alert("R:" + xhr.responseText + " S:" + status + " E:" + error);
}
});
}
});
</script>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Product</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ProductCategoryId)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.ProductCategoryId, (SelectList)ViewBag.ProductCategoriesSelectList, "Select", new { onchange = "submitform('dropdown')" })
@Html.ValidationMessageFor(model => model.ProductCategoryId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.SpecialName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.SpecialName)
@Html.ValidationMessageFor(model => model.SpecialName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.InitialPrice)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.InitialPrice)
@Html.ValidationMessageFor(model => model.InitialPrice)
</div>
<div id="partialView">
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
部分视图控制器:
public ActionResult GetProdPropertyValues(string ProdCatID, string flag)
{
if (flag == "dropdown" && !String.IsNullOrEmpty(ProdCatID))
{
ProductCategory category = db.ProductCategories.Find(Byte.Parse(ProdCatID));
if (category != null && category.ProductProperties != null)
{
return PartialView("ProdPropValues", category.ProductProperties);
}
}
return PartialView("ProdPropValues", null);
}