问题
I'm creating a simple test application so I can see how ASP.Net MVC works for what we deal with on a daily basis. We use 3rd party controls from Developer's Express, and we will continue to use them. If they absolutely do not work in ASP.Net MVC, then we will not use ASP.Net MVC.
With that said, someone has found a way to make it work. He just had to put some code in the code behind. He had to override the OnLoad event and simply just put grid.DataSource = model and grid.DataBind() and it works as expected.
In the ASP.Net MVC RC, code behind files were eliminated. I know I could put them back in... However, since people generally say that code behind files are evil, how else could you accomplish this?
回答1:
The simplest way without creating a codebehind file is to add this anywhere on your .aspx page:
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
//Initialize your control.
}
</script>
回答2:
I (seem to remember I) have seen something similar to just doing directly in the View (.aspx):
<%
grid.DataSource = Model;
grid.DataBind();
%>
Work for Telerik controls, and the proposed solution smells alot like this so maybe that will work for you?
回答3:
Any controls using ViewState will not work in ASP.NET MVC - the standard System.Web.UI.WebControls.GridView is one of them, but I don't know about the grid control in the library you're using. Just be aware that any controls that require ViewState will not function properly, because of the differences between MVC and WebForms.
Clarification: If the GridView's Viewstate and PostBack functionality is not used, it will of course function in an ASP.NET MVC View as well. However, there is no OnLoad event to override, since the page doesn't have the same life cycle, so the solution already suggested is probably the best if this control is to be used.
<%
grid.DataSource = Model;
grid.DataBind();
%>
Also make sure you have this at the top of your page.
回答4:
Here is a video and downloadable sample project showing how to use the Developer Express controls within an MVC project. Developer Express's support for MVC is supposedly forthcoming. For the time being, you have to work around issues regarding event handling and dependence on view state. But what I have been hearing recently is that they do intend to support MVC.
来源:https://stackoverflow.com/questions/566902/alternative-to-using-the-onload-event-in-an-asp-net-mvc-view