Partial View with parametrized prefix for controls names

后端 未结 4 1011
情深已故
情深已故 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:16

    You should to learn about Model Mapping in ASP.Net MVC. Everything in the asp.net mvc page will be rendered to html control therefore don't distinguish between controls in <% Html.RenderPartial("BarEditor", ViewData["bar"]); %> and <% Html.RenderPartial("BarEditor", ViewData["baz"]); %>

    0 讨论(0)
  • 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

     <form action="update">
        <div>
            <% Html.RenderPartial("BarEditor", new ViewModel.BarEditor { Prefix = "Bar", Bar = ViewData["bar"]}); %>
        </div>
        <div>
            <% Html.RenderPartial("BarEditor", new ViewModel.BarEditor { Prefix = "Baz", Bar = ViewData["baz"]}); %>
        </div>
        <input type="submit" value="Submit" />
     </form>
    

    hth

    0 讨论(0)
  • 2020-12-21 12:21

    Why not create a model for the view? Your view would then need to be a strongly typed view using the data class FormView.

    public class FormView
    {
        string Bar {get; set;}
        string Baz {get; set;}
    }
    

    Then in your view you can use

    <form action="update">
        <div>
            <% Html.RenderPartial("BarEditor", Model.Bar); %>
        </div>
        <div>
            <% Html.RenderPartial("BarEditor", Model.Baz); %>
        </div>
    
        <input type="submit" value="Submit" />
    </form>
    

    Your controller becomes

    public ActionResult Update(FormView MyForm)
    {
        ... = MyForm.Bar;
    
        ... = MyForm.Baz;
    }
    
    0 讨论(0)
  • 2020-12-21 12:23

    I would pass a string ("baz" or "bar", etc) with my ViewData when calling the user control. Have the html.textbox get its name from the text passed and its value from the value passed.

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