Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

asp.net mvc - Partial View with parametrized prefix for controls names

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

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyApp.Models.Bar>" %>
<%= Html.TextBox("a") %>
...

Now consider I need to edit two objects on one page Edit.aspx

    <form action="update">
        <div>
            <% Html.RenderPartial("BarEditor", ViewData["bar"]); %>
        </div>
        <div>
            <% Html.RenderPartial("BarEditor", ViewData["baz"]); %>
        </div>

        <input type="submit" value="Submit" />
    </form>

This submits:

a=1&a=2

I need it to be:

bar.a=1&baz.a=2

So we can process it with

public ActionResult Update(Bar bar, Bar baz)
{
    ...
}

What is a best way to write reusable BarEditor.ascx that can generate prefixes for controls names?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...