2011-09-14 60 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函数中吗? –