views:

358

answers:

1

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 no 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.

+2  A: 

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>
tvanfosson
Actually I was trying to move menu from my asp.net application to my new mvc app. The problem is not only with the linkbutton but with series of ascx files with code behind. Do you know any good resources about moving from webforms to mvc2?
kyrisu
I think the best way to go about this is probably to look at the HTML that's generated (forget the javascript code, though think about how you'd do that in an MVC context with jQuery) and either replicate that or look for an alternative that does the same thing. The http://nerddinner.com example is the prototypical MVC app and may give you some ideas on alternate implementations. Check out Phil Haack's blog as well.
tvanfosson