How to create reusable control in ASP.NET MVC

后端 未结 4 1276
有刺的猬
有刺的猬 2021-02-03 12:42

How can/should I create some \"custom control\" in ASP.NET MVC 3? I have red about partial views, ViewUsersControl, Html.RenderAction, but I still don\

相关标签:
4条回答
  • 2021-02-03 13:17

    In addition to all the other answers for this post, I can offer you the use of EditorFor and DisplayFor templates. These are useful when you want to easily render or edit a custom type. It'll handle validation nicely (which can get weird when using partials) and you can nest them recursively (again another feature that isn't obviously handy until you need it).

    You can also use Html.RenderAction() or Html.Action() to call another controller action within a view and display the results in-line in the page. This is probably the closest to what you need as it allows you to render a partial, include code in the controller and it also allows for the passing of parameters.

    Links to:

    DisplayFor and EditorFor Templates

    Action and RenderAction

    0 讨论(0)
  • 2021-02-03 13:18

    You may use

    @{Html.RenderPartial("YourCustomView",YourModel);}
    

    For instance, In your Shared folder create a new View and name it "_MyCustomControl"

    Then in the code write :

    @model YourNameSpace.Models.YourModel
    
    @{
        Layout = null;
    }
    
    @*Here write your control's markup*@
    

    Then in your Views where you want to use this "control" you add:

    @{Html.RenderPartial("_MyCustomControl",new YourModel { args });}
    

    If you get into trouble with RenderPartial check this out

    0 讨论(0)
  • 2021-02-03 13:21

    As you have mentioned that you can use Partial Views. Yes you can use Partial Views, which is the most effective and efficient way.

    For Ajax rendering you can always use

         @using (Ajax.BeginForm("Details", new { id = Model.Post.PostId }, new AjaxOptions    
      {
    

    Few of the links you would like to see

    Rendering partial view in ASP.Net MVC3 Razor using Ajax

    Render Partial Views using JQuery in MVC3

    0 讨论(0)
  • 2021-02-03 13:25

    1) PartialViews

    2) Custom Html helpers

    3) Child Actions

    Update ASP.NET Core:

    2) Tag Helpers are preferred way over Custom Html helpers

    3) View Components are used instead of Child Actions

    0 讨论(0)
提交回复
热议问题