Why user control with code behind file doesn't want to compile under MVC2?
I have user control in my MVC2 app placed in the Content folder (it's not supposed to be a view, just reusable part of the app).
UserControl1.ascx looks like:
<@ Control AutoEventWireup="true" Language="C#" CodeFile="~/Content/UserControl1.ascx.cs" Inherits="MVCDrill.Content.UserControl1" %>
<div runat="server" id="mydiv">
<asp:LinkButton id="lb_text" runat="server"></asp:LinkButton>
</div>
UserControl1.ascx.cs looks like:
using System;
using System.Web;
using System.Web.UI;
namespace MVCDrill.Content
{
public class UserControl1 : UserControl
{
public string Text
{
get { return this.lb_text.Text; }
set { this.lb_text.Text = value; }
}
}
}
I'm pretty sure this kind of stuff compiled under webforms but I'm getting compilation error:
'MVCDrill.Content.UserControl1' does not contain a definition for 'lb_text' and n开发者_运维问答o extension method 'lb_text' accepting a first argument of type 'MVCDrill.Content.UserControl1' could be found (are you missing a using directive or an assembly reference?)
Am I missing something? How to change it (what is the alternative) in MVC2 ?
p.s. Intellisense sees lb_text with no problem. I've tried with different controls with the same outcome.
The "correct" way to implement this type of functionality is to use a partial view in the Shared view folder -- with no codebehind -- and supply the data with a view model.
Ex:
<%@ Page Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<LinkButtonModel>" %>
<div id="mydiv">
<a href="#" id="lb_text"><%= Model.LinkButtonText %></a>
</div>
<script type="text/javascript">
$(function() {
$('#lb_text').click( function() {
$(this).closest('form').submit();
});
});
</script>
精彩评论