ASP.Net MVC Ajax.BeginForm OnComplete在Razor视图中传递c#参数

时间:2013-04-11 11:35:39

标签: c# asp.net-mvc razor

我在MVC c#Razor视图中有以下代码:

@{string url = "/Projects/_MonthRangesScriptsPartial";}
@using (Ajax.BeginForm(
  "_MonthRanges", 
  "Projects", 
  new { id = ViewBag.InputResourceID }, 
  new AjaxOptions { 
    HttpMethod = "POST", 
    UpdateTargetId = "MonthRanges", 
    InsertionMode = InsertionMode.Replace,
    OnComplete = "updategraphArrayScript(@url,@ViewBag.InputResourceID)"
  }))

代码几乎完美无缺,但我想将c#变量解析为OnComplete行中的值。

也就是说,Razor engin应该将代码解析为(例如):

<form action="/Projects/_MonthRanges/55" 
  data-ajax="true" data-ajax-complete="updategraphArrayScript(/Projects/assets,55)"
  ...>

而不是:

<form action="/Projects/_MonthRanges/55" 
  data-ajax="true" data-ajax-complete="updategraphArrayScript(@url,@ViewBag.InputResourceID)"
  ...>

2 个答案:

答案 0 :(得分:3)

只需创建另一个变量字符串:

@{
    string url = "/Projects/_MonthRangesScriptsPartial";
    string onComplete = String.Format("updategraphArrayScript({0}, {1})", url, ViewBag.InputResourceID);
}

@using (Ajax.BeginForm(
  "_MonthRanges", 
  "Projects", 
  new { id = ViewBag.InputResourceID }, 
  new AjaxOptions { 
    HttpMethod = "POST", 
    UpdateTargetId = "MonthRanges", 
    InsertionMode = InsertionMode.Replace,
    OnComplete = @onComplete
  }))

答案 1 :(得分:0)

在分配OnComplete值时取消@。您不需要它,因为您已经在服务器端代码的上下文中。

@用于将html呈现上下文切换为服务器端代码,<text></text>用于从服务器端上下文切换到html呈现。在上面给出的示例中,您已经在BeginForm()方法的服务器端代码上下文中,因此不需要@。您没有将onComplete的值写入页面,BeginForm()将处理所有这些。