Asp.Net WebForms - How to pass ViewData as param t

2019-06-13 19:42发布

问题:

I am new to ASP.net and have inherited an app to update. I'm going quite well though have struck a situation I need some help understanding.

I have a user control uc:speciesgrid that takes some arguments: applicationId and species should be from ViewData and passed as arguments, however I cannot find a syntax that works. A hardcoded call to it (that works) is:

<uc:speciesgrid runat="server" ID="speciesgrid1" applicationId="6191" species="Dog"/>

I tried all combinations of <%, <%=, <%# and none will work. So something like:

<uc:speciesgrid runat="server" ID="speciesgrid1" applicationId='<%AppData["NoiId"]%>' species="Dog"/>

The errors are all the same:

{"Cannot create an object of type 'System.Int32' from its string representa{ion 'ViewData[\"NoiId\"]' for the 'applicationId' property."}

It is obvious that whatever I've included is being interpreted literally rather than having the server substitute in the value.

I also tried setting a variable and using that but the error is the same.

<%
var applicationId = ViewData["NoiId"];
%>

What IS working is accessing ViewData['NoiId'] in the User Controller:

protected void Page_Load(object sender, EventArgs e)
{
    ...
    Debug.WriteLine("In the controller, ViewData['NoiId'] is: " + ViewData["NoiId"]);
}

> In the controller, ViewData['NoiId'] is: 6191

It would seem to me that:

  • User Controls are built initialy on the server "before" that application starts. Hence why I can't pass any <% arguments.
  • And to pass arguments the only way is through ViewData and similar mechanisms that are interpreted later in the life cycle "at run time".

However I'd prefer pass arguments as parameters if at all possible.

Is it possible? Or is my understanding in that paragraph 2 above correct?

回答1:

I think you use MVC pattern in ASP.NET and you tend to pass parameter from View to UserControl. For do it, you can not use code below in view page:

<uc:speciesgrid runat="server" ID="speciesgrid1" applicationId="6191" species="Dog"/>

Because view page has not code behind. For pass parameter to UserControl, you can use this code:

<% Html.Partial("~/Views/Home/SpeciesGridController.ascx", ViewData["NoiId"]); %>

Html.Partial or Html.RenderPartial used for load ascx or Partial View in ASP.NET MVC. Then you can get ViewData["NoiId"] and set this to variable or property of ascx in Page_Load like this: