ASP.Net MVC Ajax.BeginForm OnComplete pass c# argu

2019-07-07 02:44发布

问题:

I have the following code in a MVC c# Razor view:

@{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)"
  }))

The code works almost perfectly, but I would like to resolve the c# variables to their values in the OnComplete line.

That is to say, the Razor engin should resolve the code to (for example):

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

Rather than:

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

回答1:

Simply create another variable string:

@{
    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
  }))


回答2:

Take off the @ when you assign your OnComplete value. You don't need it since you're already in the context of server side code.

@ is used to switch html rendering context to server side code, and <text></text> is used to switch from server side context to html rendering. In example given above, you're already in the server side code context of the BeginForm() method so the @ is not needed. You're not writing the value of onComplete to the page, BeginForm() will handle all that.