[英]@Html.Dropdownlist C# MVC 4 Show div when bool = true
[英]C# MVC4: Replace <div> when selection is made from a Html.DropDownList using jQuery
从下拉列表中选择相应的字符串(延迟加载)后,我需要能够将数据填充到对象的<div>
或其他某种类型的部分中。
在下拉列表中进行更改时,我希望调用控制器中的方法,该方法将使用方法的输出填充<div id=result></div>
。
也许我正在错误地解决这个问题。 我怀疑问题出在我的JavaScript中。 这是我的方法:
视图:
<div>@Html.DropDownList("MyDDL") </div>
<br>
<div id="result"></div>
JavaScript的:
<script type ="text/javascript">
$(document).ready(function () {
$("#MyDDL").change(function () {
var strSelected = "";
$("#MyDDL option:selected").each(function () {
strSelected += $(this)[0].value;
});
var url = "HomeController/showInfo";
//I suspect this is not completely correct:
$.post(url, {str: strSelected},function (result) {
$("result").html(result);
});
});
});
</script>
控制器(也许我不应该使用PartialViewResult
):
public ActionResult Index()
{
List<string> myList = new List<string>();
List<SelectListItem> MyDDL = new List<SelectListItem>();
myList.Add("Tim");
myList.Add("Joe");
myList.Add("Jim");
//fill MyDDL with items from myList
MyDDL = myList
.Select(x => new SelectListItem { Text = x, Value = x })
.ToList();
ViewData["MyDDL"] = MyDDL;
return View();
}
[HttpPost]
public PartialViewResult showInfo(string str)
{
Person p = new Person(str); //name is passed to constructor
p.LoadInfo(); //database access in Person Model
ViewBag.Info = p.Info;
return PartialView("_result");
}
_result.cshtml:
<p>
@ViewBag.Info
</p>
谢谢。
稍微更改一下脚本。 jQuery选择器中的结果div缺少#。 使用下面给出的代码
$.post(url, {str: strSelected},function (result) {
$("#result").html(result);
});
我认为,如果javascript在本地,则不需要放$ .post(url,{str:strSelected},function(result){
您可以使用
//I suspect this is not completely correct:
$("#result").html(result);
试试吧
您是否尝试调试p.LoadInfo()
是否有价值? 对于您的脚本,我也有一些建议:
尝试在事件中添加keyup
,以便在使用箭头键并单击时可以获取该值:
$("#MyDDL").on("change keyup", function () {
// you can get the dropdown value with this
var strSelected = $(this).val();
因此,我进行了以下更改并成功运行:
视图:
<div><%= Html.DropDownList("MyDDL") %> </div>
<br>
<span></span>
JavaScript的:
<script type ="text/javascript">
$(document).ready(function () {
$("#MyDDL").change(function () {
var strSelected = $("#MyDDL option:selected").text();
var url = "/Home/showInfo";
$.post(url, {str: strSelected},function (result) {
$("span").html(result);
});
});
});
_result.cshtml:
@ViewBag.Info
控制器保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.