Partial View with parametrized prefix for controls names

后端 未结 4 1015
情深已故
情深已故 2020-12-21 11:48

I have a BarEditor.ascx, that can be called from diffent places.

<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl

        
4条回答
  •  滥情空心
    2020-12-21 12:18

    just create a ViewModel class for your BarEditor and make it strongly typed to this new class

    e.g.

    namespace ViewModel {
        public class BarEditor {
    
            string Prefix { get; set; }
            Models.Bar Bar { get; set; }
        }
    }
    

    now you create your textbox in BarEditor.ascx like this

    <%= Html.TextBox(Model.Prefix + ".a") %> 
    

    and in your view you include the BarEditor like that

     
    <% Html.RenderPartial("BarEditor", new ViewModel.BarEditor { Prefix = "Bar", Bar = ViewData["bar"]}); %>
    <% Html.RenderPartial("BarEditor", new ViewModel.BarEditor { Prefix = "Baz", Bar = ViewData["baz"]}); %>

    hth

提交回复
热议问题