[英]How to postback to a controller function when a value is selected from dropdown
我在視圖上創建了一個下拉列表並顯示一個列表。
@Html.DropDownListFor(m => m.SelectedId, new SelectList(Model.List, "ID", "Name"))
當用戶從下拉列表中選擇值時,我想刷新頁面。 我不知道如何在不單擊任何按鈕的情況下將選擇事件從下拉菜單映射到控制器功能。
在視圖加載時,有一個控制器功能,該功能使用列表填充視圖。
public ActionResult Populate()
{
List<string> list = get it from sql server
ViewModel viewModel = new ViewModel();
viewModel.list = list;
return view();
}
但是如何調用控制器函數,該函數將選定的值作為ID並檢索數據並刷新結果頁面。
$(document).ready(function() {
$("#ddl").change(function() {
var strSelected = "";
$("#ddl option:selected").each(function() {
strSelected += $(this)[0].value;
});
var url = "/Home/MyAction/" + strSelected;
$.post(url, function(data) {
// do something if necessary
});
});
});
要么
<%=Html.DropDownListFor(m => m.SelectedId, new SelectList(Model.List, "ID", "Name"), new { onchange="this.form.submit();" })%>
將其添加到頭部的布局中:
<script type="text/javascript">
$(document).ready(function () {
$('select:[autopostback=true],input[type=checkbox]:[autopostback=true],input[type=radio]:[autopostback=true]').live('change',function () {
$(this).closest('form').submit();
});
});
</script>
在您看來:
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.SelectedId, new SelectList(Model.List, "ID", "Name"), new { autopostback = "true" })
}
更改下拉列表的選擇時,將提交下拉列表所在的表單。 如果該表單的操作結果在同一頁面上,則將使用任何要更新的內容重新加載該頁面
這很簡單。 在您的JavaScript中,您具有:
$(document).ready(function () {
$('#SelectedId').change(function () {
var id = $(this).val();
$.getJSON("/YourController/YourAction", { id: id},
function (data) {
$("#SomeDivSelector").html(data);
});
});
});
您的控制器應如下所示:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult YourAction(int id)
{
//do something
return Json(ControlToString("~/Views/YourController/YourView.cshtml", yourModelWithData), JsonRequestBehavior.AllowGet);
}
並定義了ControlToString:
private string ControlToString(string controlPath, object model)
{
//CshtmlView control = new CshtmlView(controlPath);
RazorView control = new RazorView(this.ControllerContext, controlPath, null, false, null);
this.ViewData.Model = model;
using (System.Web.UI.HtmlTextWriter writer = new System.Web.UI.HtmlTextWriter(new System.IO.StringWriter()))
{
control.Render(new ViewContext(this.ControllerContext, control, this.ViewData, this.TempData, writer), writer);
string value = ((System.IO.StringWriter)writer.InnerWriter).ToString();
return value;
}
}
問候。
您要應用的內容與所用技術的概念背道而馳。 基於ASP.NET技術的MVC,但是另一種執行方式。 MVC不會使用ASP.NET更好的生命周期,因此,不會“回發”。 MVC-在基於架構模式的根源中,它允許將任何系統的不同層分開,因此,當前技術上的開發方法完全不同。 了解有關MVC的更多信息: http : //www.asp.net/mvc
如果仍要解決問題,則可以使用ASP.NET概念並使用DropDownList控件的AutoPostback屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.