Encapsulating user controls in ASP.NET MVC

Sorry if this is the main question - I am having trouble moving to ASP.NET MVC from the page frame.

In the page structure, I often use ASCX files to create small encapsulated pieces of functionality that can be included in various places on the site. If I am building a page and I need one of these controls - I just add a link and everything just works.

As far as I can tell, in MVC, an ASCX file is only a partial representation. Does this mean that wherever I want to add one of these units of functionality, I also need to add code to the controller action method to make sure that the corresponding ViewData is available for ASCX?

If so, it seems to me that this is a little step back. This means, for example, that I could not simply β€œdrop” the control onto the main page without having to add code for each controller whose views use this main page!

I suspect I am missing something - any help would be appreciated.

Thank you, Chris

+5
source share
3 answers

As far as I can tell, in MVC, an ASCX file is only a partial representation. Does this mean that wherever I want to add one of these units of functionality I also need to add code to the controller action method to make sure that the corresponding ViewData is available for ASCX?

Yes.

RenderAction RenderPartial ( , -) .

, , , , .

+3

, , , .

, " " ASP.NET MVC? "HtmlHelper". , "FirstName", , :

<%= Html.Textbox("FirstName") %>

.

, . , HtmlHelper, :

public static class HtmlHelperExtensions
{
    public static string Bold(this HtmlHelper html, string text)
    {
        return "<b>" + text + "</b>\n";
    }
}

, , , , :

<%= Html.Bold("This text will be in bold-face!") %>

, . . , (ex: enum Gender { Male, Female }, - Gender: <%= Html.EnumDropDown(Model.Gender) %>).

!

+3

.

<% Html.RenderPartial("MyPartial", ViewData["SomeObject"]);

(.ascx) "" ( , @Control), , , .

, , Model, , .

( .aspx) ViewData, .

, , :

<% Html.RenderAction("MyAction", "MyController", new { Parameter1="Value1"}) %>

, Action, , RenderAction(). , , .

Google "renderaction and renderpartial" for more information.

+1
source

All Articles