本文介绍了局部视图与参数化preFIX控件名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个BarEditor.ascx,可以从diffent位置调用。

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") %>
...

现在认为我需要在一个页面上Edit.aspx

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>

本提交:

a=1&a=2

我需要它是:

bar.a=1&baz.a=2

因此​​,我们可以处理它

So we can process it with

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

什么是编写可重用BarEditor.ascx可以生成控件名称prefixes一个最好的方式?

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

推荐答案

只要创建一个视图模型类为您BarEditor,使它强类型的这一类新的

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

例如

namespace ViewModel {
    public class BarEditor {

        string Prefix { get; set; }
        Models.Bar Bar { get; set; }
    }
}

现在你BarEditor.ascx创建文本框像这样

now you create your textbox in BarEditor.ascx like this

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

和在你看来,你包括像的BarEditor

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>

心连心

这篇关于局部视图与参数化preFIX控件名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 15:32