2011-09-14 59 views
2

我有一個下拉列表,如果更改,應該刷新視圖的模型。這裏是控制器:ASP.NET MVC3 - DropDownList使用jQuery刷新模型

public ActionResult Index() 
    { 
     //do something totally awesome 
    } 

    [HttpPost] 
    public ActionResult Index(int user) 
    { 
     //do something even more awesome with the new value selected from the drop down list 
    } 

觀的相關部分:

<div id="selectuser" class="user-input">@Html.DropDownListFor(x => x.SelectedUser, Model.Users)</div> 

和jQuery來處理下拉列表改變:

$(function() { 
    $('#selectuser select').change(function() { 
     $.post('@Url.Action("Index", "Home")', { user: $(this).val() }, function (result) { 

     }); 
    }); 
}); 

看來,一切工作,除了jQuery部分。顯然,UrlAction(...)是不正確的。當用戶更改選擇時,這是MVC嘗試加載的URL:http://localhost:5555/@Url.Action%28%22Index%22,%20%22Home%22%29

我期待MVC在選擇更改時路由到控制器中的HttpPost Index操作。爲什麼不呢?我如何解決它?

我是一個總noob在這 - 你的幫助是不勝感激。

回答

2

這裏發生的是,剃刀發動機沒有評估@ Url.Action()。如果我不得不猜測,我會說,無論生成JavaScript代碼是不是在相同的剃刀視圖。如果你還沒有,我會先把代碼移到視圖頁面上的一個塊中,如果你還沒有的話。從原始帖子中不清楚JQuery代碼是否在視圖中。

+0

就是這樣!謝謝。該腳本在另一個文件中。在視圖中將腳本移動到

0

您是否嘗試過使用ajax回調函數?

$('#selectuser select').change(function() { 
    $.ajax({ 
     url: '@Url.Content("~/Home/Index")', 
     type: "POST", 
     data: val, 
     datatype: "json", 
     success: function (data, status, request) { 
      // success code here 
     }, 
     error: function (request, status, error) { 
      // error code here 
     } 
    }); 
} 

這裏將是返回JSON控制器功能(指數)的例子:

[HttpPost] 
public JsonResult Index(int val) 
{ 
    try 
    { 
     // do what you need to here 

     return Json(new 
     { 
      // Returning a partial view and success 
      Html = this.RenderPartialView("_PartialView", model), 
      Success = true 
     }); 
    } 
    catch (Exception ex) 
    { 
     return Json(new 
     { 
      // Returning a partial view and and error 
      Html = this.RenderPartialView("_PartialView", model), 
      Success = false 
     }, JsonRequestBehavior.AllowGet); 
    } 
} 

我加了下面一些例子櫃面你必須使用一個ActionResult,不能使用JsonResult。

http://blogs.us.sogeti.com/swilliams/2009/05/11/different-action-results-with-asp-net-mvc-and-jquery/

http://iridescence.no/post/Invoking-ASPNET-MVC-Actions-from-JavaScript-using-jQuery.aspx

Return ActionResult to a Dialog. ASP.NET MVC

+0

感謝您的回覆。我不確定如何添加ajax會有所幫助。唉,我嘗試使用上面的腳本,並在我現有的控制器中設置了一個永不被擊中的斷點。該錯誤基本上是相同的(HTTP 500),因爲這是它試圖打開的URL:http:// localhost:5555/@Url.Content%28%22~/Home/Index%22%29 – Noel

+0

我想你在你的MVC 3應用程序中缺少一些東西。它不應該這樣出來。嘗試創建一個新的MVC 3應用程序,看看它是否仍然存在。 – TIHan

+0

同意TIHan,沒有理由你的網址應該是這樣的。你的項目中是否有所有必要的jquery引用?你有沒有在你的jQuery中加入一個斷點來看看它究竟做了什麼?你的jQuery在ready或pageLoad函數中嗎? –