我有一個控制器與Index
行動,它返回ViewModel
和GetCategories
行動應該返回一個局部視圖。從下拉控件中選擇後顯示項目在同一頁面
因此,這裏是我的CategoryController.cs
文件:
public class CategoryController : Controller
{
public ActionResult Index()
{
CategoryViewModel ob = new CategoryViewModel();
ob.LoadLanguages();
return View(ob);
}
public ActionResult GetCategories(int langID)
{
CategoryViewModel ol = new CategoryViewModel();
ol.LoadCategoriesByLanguage(langID);
if (Request.IsAjaxRequest())
return PartialView("GetCategories",ol);
在我Index.cshtml
鑑於我創建了一個下拉列表,然後,當用戶選擇一個元素,它使一個Ajax請求getCategories
行動和成功,我應該加載GetCategories
局部視圖。問題是它將我重定向到一個新頁面,我無法再看到我的下拉菜單。
這裏是我的Index.cshtml
文件:
@model Onion.Web.ViewModels.CategoryViewModel
<script>
$(document).ready(function() {
$("#ddlLanguages").change(function() {
$.ajax({
type: 'GET',
url: '@Url.Action("GetCategories")' + '?langId=' + this.value,
data: {},
success: callbackFuntion('@Url.Action("GetCategories")' + '?langId=' + this.value),
error: function() { alert('Error'); }
});
});
});
function callbackFuntion(url){
window.location = url;
}
</script>
@Html.DropDownList("Languages", new SelectList(Model.lstLanguages, "LanguageID", "Name"), "SELCT LANGUAGE----->",new { id = "ddlLanguages" })
}
這裏是我的Category.cshtml
文件:
@model Onion.Web.ViewModels.CategoryViewModel
<table>
<tr>
<td>ID</td>
<td>Title</td>
</tr>
@foreach (var item in Model.lstCategoryLanguages)
{
<tr>
<td>@item.Title</td>
<td>@item.ShortDescription</td>
</tr>
}
</table>
I can't beleve how easy it is in web forms and here i'm struggling for hours. Is there a better way to do all this. Thank you in advance
你有問題是重定向成功了新的動作。 ajax的優點是使用結果並使用jQuery將其直接寫入到您的html控件中。 ramiramilu顯示它是如何工作的。 –