开发者

ASP.NET MVC : Good Replacement for User Control?

I found user controls to be incredibly useful when working with ASP.NET webforms. By encapsulating the code required for displaying a control with the markup, creation of reusable components was very straightforward and very, very useful.

While MVC provides convenient separation of concerns, this seems to break encapsulation (ie, you can add a control without adding or using its supporting code, leading to runtime errors). Having to modify a controller every time I add a control to a view seems to me to integrate concerns, not separate them. I'd rather break the purist MVC ideology than give up the benefits of reusable, packaged controls.

I need to be able to include components similar to webforms user controls throughout a site, but not for the entire site, and not at a level that belongs in a master page. These components should have their own code not just markup (to interact with the business layer), and it would be great if the page controller didn't need to know about the control. Since MVC user controls don't have codebehind, I can't see a good way to do this.

Update FINALLY, a good (and, in retrospect, obvious) way to accomplish this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace K.ObjectModel.Controls
{
    public class TestControl : ViewUserControl
    {
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            writer.Write("Hello World");
            base.Render(writer)开发者_JAVA百科;
        }
    }
}

Create a new class which inherits ViewUserControl

Override the .Render() method as shown above.

Register the control via its associated ASCX as you would in a webForm:

<%@ Register TagName="tn" TagPrefix="k" Src="~/Views/Navigation/LeftBar.ascx"%>

Use the corresponding tag in whatever view or master page that you need:

<k:tn runat="server"/>

Make sure your .ascx inherits your new control:

<%@ Control Language="C#" Inherits="K.ObjectModel.Controls.TestControl" %>

Voila, you're up and running. This is tested with ASP.NET MVC 2, VS 2010 and .NET 4.0.

Your custom tag references the ascx partial view, which inherits from the TestControl class. The control then overrides the Render() method, which is called to render the view, giving you complete control over the process from tag to output.

The difference between using this approach and calling Html.RenderPartial() or `Html.RenderAction()' is adding the control to a view is done with a webforms-like tag, which is not only more comfortable for designers, but keeps them from having to be aware of controller names and methods. The name of the control class is isolated to the ASCX, also making it easier to drop these in an assembly and reuse them across separate projects.

Some may say that this violates SoC, but I believe that this approach is functionally equivalent to tying a partial view and a controller together while maintaining clean markup. It should be clear, however, that it is still up to the developer to keep only presentation-related logic in the control Business and data access logic still belong in their respective layers.


I'm a little confused here.

First of all, the .NET MVC equivalent to User Controls is Partial Views. Partial Views are a convenient way of encapsulating common View functionality in a single location. You can then call a Partial View from inside another View.

Second of all, modifying a View shouldn't mean also modifying a controller. If you are required to make a change to both just because your View changed (and not the underlying data), then there's a code issue somewhere along the line.


At first glance its easy to dismiss MVC as not having the capabilities for reusable components.

Once you get the know ASP.NET MVC you'll find there are several techniques for creating rich controls and components and encapsulating aspects of MVC follow along the same pathways as encapsulating a WebForms application.

I think what you're doing is only looking at the View aspects of MVC and not how all the underlying M and C can be encapsulated and tied together. Partial Views, Render Action/Partial are just small pieces of the underlying component capabilities of MVC. There is much more richness under the covers.


a user control is just some stuff that renders html, in mvc you have html helpers and partial views and normal views (you can render them with renderaction )

Html.Helper("someStuff")
Html.RenderPartial("viewname")
Html.RenderAction<Controller>(o => o.Action());

so basically it's just the helpers

you can actually easily substitute a call to

Html.TextBoxFor(o => o.Name);

with

Html.RenderPartial("textbox", Model.Name);


Consider the following example:

  • My view (CustomerDetail.ascx) binds to ICustomerDetail view-model which looks like:

    interface ICustomerDetail {
    string Name { get; }
    Address CurrentAddress { get; }
    }

  • I can create a partial view Address.ascx which binds to IAddress view-model

  • When I am creating the CustomerDetail.ascx, I can place the Address.ascx on the same surface & bind it to the oCustomerDetail.Address field

  • IMO - we should be composing views from multiple such smaller partial views in MVC & this is where you will see the re-usability & the power of user controls (partial views)

  • Now if my controller returns ICustomerDetail, I will be able to re-use the Address.ascx without any problems

HTH.


Let's take a registration page for an e-commerce site, as an example. You prompt the user for their name, password, postal information, favorite dog breed, etc. Somewhere else in the application, you also need to collect a billing address and a shipping address. To enforce DRY, you create a user control that manages the entry of the address information.

So, to further illustrate, your address class looks something like this:

public class Address
{
    public string StreetAddress { get; set; }
    public string City { get; set; }
    ...
}

Your registration class:

public class UserReg
{
    public string UserName { get; set; }
    public Address MailingAddress { get; set; }
    ...
}

Your billing and shipping addresses may descend from the Address class:

public class BillingAddress : Address
{ 
    ...
}

public class ShippingAddress : Address
{ 
    ...
}

For the following examples, I am assuming that you have added System.Web.Mvc to the namespaces section of web.config. Based on this class hierarchy, your user control will have a control tag that refers only to the Address class:

<%@ Control Language="C#" Inherits="ViewUserControl<Address>" %>

Since you've done this, you simply need to pass the appropriate model reference from the page. In the User Registration page:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="ViewPage<UserReg>" %>
    ...
    <% Html.RenderPartial("AddressControl", Model.MailingAddress); %>

In the billing address page:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="ViewPage<BillingAddress>" %>
    ...
    <% Html.RenderPartial("AddressControl", Model); %>

In the shipping address page:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="ViewPage<ShippingAddress>" %>
    ...
    <% Html.RenderPartial("AddressControl", Model); %>

I can pass the model directly from the billing and shipping page, because the class directly descends from Address. As long as the logic is in place to process the addresses correctly, you're not going to have to make many changes to the controller, if any.


Partial views are certainly not close to WebUserControls.

In WebUserControls, you can write the HTML, and its own event handlers and is also connected to the parent page. For e.g. I can create a Sign In Web user control and use it anywhere in the web application. As an independent control, it can handle all the verifications and signing and allows redirections.

You don't get that in Partial views.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜