ASP.NET MVC视图用户控件 - 如何设置的ID? [英] ASP.NET MVC View User Control - how to set IDs?

查看:702
本文介绍了ASP.NET MVC视图用户控件 - 如何设置的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要我的网页上一个下拉列表,让用户选择他们的状态。由于这是可能会在其他地方使用的控制,我认为这将是创建一个MVC视图用户控件能够重用的一个好主意。

I need a dropdown list on my page that will allow a user to select their state. Since this is probably a control that will be used elsewhere, I thought it would be a good idea to create an MVC View User Control that could be reused.

我想控制会是这个样子:

I was thinking the control would look something like this:

<select name="" id="">
   <option value="AL">Alabama</option>
   <option value="AK">Alaska</option>
</select>

和在我看来,code会是这样的:

And the code in my view would be something like:

<%= Html.RenderPartial("StateDropdownControl") %>

我的问题是,什么是设置在控制的名称和ID的最佳方式?我要确保我能有一个页面上此控件的多个实例,如果需要的话。另外,我希望能够在默认情况下应选择的状态来发送。

My question is, what's the best way to set the name and id on the control? I'd want to make sure I could have multiple instances of this control on one page, if needed. Also, I'd want to be able to send in the state that should be selected by default.

我会做的ViewData它以某种方式?

Would I do it with ViewData somehow?

推荐答案

科瑞,是对正确的解决方案。我想声明的具体型号为对象,你的观点,使观点很简单,作为一个方面的奖金,使他们很容易污垢测试。

Corey is on to the right solution. I think declaring specific Model objects for your view makes the views VERY simple and as a side bonus makes them dirt easy to test.

因此​​,而不是刚好路过的ID为对象,你可能想创建自己的模型对象传递。

So instead of just passing the ID as the object, you'd probably want to create your own Model object to pass in.

这可能是这个样子:

public class StateDropDownPresentationModel
{
    public string DropDownID { get; set; }
    public string SelectedState { get; set; }
}

显然,继续添加任何你需要这种模式,让您的观点是正确的。

Obviously, keep adding whatever you need to this model to make your view correct.

然后,你可以这样调用它:

Then, you could call it like this:

<%= Html.RenderPartial("/someDirectory/SomeControl.ascx", new StateDropDownPresentationModel { DropDownID = "MyID", SelectedState = "IL" } %>

然后只是确保你把检查之类的ID为空/空(即或许应该抛出一个错误),并SelectedState被空/空。

Then just make sure you put in checks for things like ID being null/blank (that should probably throw an error) and SelectedState being null/blank.

这篇关于ASP.NET MVC视图用户控件 - 如何设置的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆