@ Html.DropDownListFor基本用法 [英] @Html.DropDownListFor Basic Usage

查看:171
本文介绍了@ Html.DropDownListFor基本用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习MVC4我必须承认我有点被所有的拉姆达前pressions,泛型和匿名类型的依赖的挑战,尤其是当有许多重载函数。这是一个有点混乱,试图了解的HTML辅助工作。就拿DropDownListFor助手,例如。我试图从我的code提取要领。这就是为什么你看到的只是一个只有一列,性别,在表中。但愿它仍然是语法正确的:

I'm just starting to learn MVC4 and I must admit I'm a little challenged by all the reliance on lambda expressions, generics and anonymous types, especially when there are many overloaded functions. It's a bit confusing to try and understand how the HTML Helpers work. Take the "DropDownListFor" Helper, for example. I tried to extract the essentials from my code. That's why you see only a only a single column, "Gender", in the table. Hopefully it is still syntactically correct:

@model IEnumerable<BusinessLayer.Employee>
<table>
    @foreach (var employee in Model) 
    {    
        <tr>
            <td>
            @{

                var listItems = new List<SelectListItem>()
                {
                    new SelectListItem {Text = "Male",   Value = "M"},
                    new SelectListItem {Text = "Female", Value = "F"}
                };

                @Html.DropDownListFor(m => employee.Gender, listItems, listItems.Find(i => i.Value == employee.Gender).Text)                          
            }  

            </td>
        </tr>
    }
</table>        

有在Model对象两名员工,产生员工的IEnumerable和下面的HTML

There are two Employees in the Model object, an IEnumerable of Employee and the following HTML is generated

<table> 
    <tr>
        <td>
            <select id="employee_Gender" name="employee.Gender"><option value="">Male</option>
                <option value="M">Male</option>
                <option value="F">Female</option>
            </select>
    </tr>       
        </td>    
             <select id="employee_Gender" name="employee.Gender"><option value="">Female</option>
                <option value="M">Male</option>
                <option value="F">Female</option>
             </select>                
        </td>
</table>                

综观DropDownListFor方法的第一个参数,

Looking at the first param of the DropDownListFor Method,

@Html.DropDownListFor(m => employee.Gender, ...

...难道我理解正确的M重新presents被传递到视图模型类的实例?在我所看到的在线实施例中,我看到的例子,其中m的显示来表示模型类,但其中,该模型是一个实例的类,例如,一个单一的Employee对象,而不是作为雇员的集合在这里我想显示员工表清单这里的情况。我假设的DropDownListFor方法的第一个参数的目的是点/绑定,以在模型中的属性的,所以这就是为什么我做M => employee.Gender。请问这是什么我应该做的事时,该模型是员工的集合,而不是单一的员工吗?如果是这样,我很困惑,我怎么能生成唯一ID的两个下拉其中均被分配employee_Gender的名称和两个列表ID属性。

...Do I understand correctly that the "m" represents the instance of the model class that was passed into the View? In the online examples that I have seen, I have seen examples where the "m" appears to refer to the model class but where the model is a single instance class, for example, a single Employee object, rather than a collection of Employees as is the case here where I want to display a table list of Employees. I'm assuming that the intent of the first param of the DropDownListFor Method is "point/bind' to a property in the model, so that's why I made m => employee.Gender. Is this what I should be doing when the model is a collection of Employees rather than a single Employee? If so, I am confused as to how I can generate unique IDs for the two drop down lists which were both assigned "employee_Gender" for both the NAME and ID attributes.

有关助手DropDownListFor的第三个参数,

For the 3rd parameter of the Helper DropDownListFor,

listItems.Find(i => i.Value == employee.Gender).Text

这是合理的?对于employee.Gender的值是M或F,但显示的内容是男性和女性。我很困惑这个参数是否用于指定一个默认的否选择第一个值或者这是否param用于从下拉当前员工的价值选择---或许这可以一举两得?例如,它选择的文本的规定,如果找到否则添加指定为文本的 FIRST?的参数,如果该值没有发现?这似乎是从我所看到的是如何工作的。可这第三个参数进行简化或者是我的榜样合理?

Is this reasonable? The value for employee.Gender is either "M" or "F" but the display Text is "Male" and "Female." I am confused whether this param is used to specify a default "NO SELECT" first value or whether this param is used to select from the drop down the value of the current Employee---or perhaps it can do both? For example, does it select the Text specified if found and otherwise add the text specified as the FIRST? parameter if the value is not found? That appears to be how it works from what I see. Can this 3rd param be simplified or is my example reasonable?

感谢您阅读我的问题很多乱舞,试图更好地理解这是你的耐心。

Thanks for your patience in reading my many flurry of questions in trying to better understand this.

推荐答案

你并不孤单。 Lambda表达式+ MVC使编码邪恶容易,但他们也使它看起来相当神奇(由于抽象)。

Part 1: Explaining Lambda magic

You're not alone. Lambdas + MVC make coding wicked easy, but they also make it seem rather magical (due to the abstraction).

纵观DropDownListFor方法[...]我是否理解正确的M重新presents被传递到视图模型类的实例?

Looking at the first param of the DropDownListFor Method [...] Do I understand correctly that the "m" represents the instance of the model class that was passed into the View?

HTML助手+ lambda表达式的剃刀,因为他们走了一条捷径,并没有真正揭示你这是怎么回事是简单而神奇的。

HTML Helpers + Lambdas in Razor are simple and magical because they are taking a shortcut and not actually revealing to you what's going on.

首先,让我们来看看 @Html 。我们知道 @ 开始了我们的剃刀语法,然后 HTML 是魔术。其实, HTML 是<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper%28v=vs.108%29.aspx\">HtmlHelper即自动初始化,并给你的对象。更具体地说,它是一个的HtmlHelper&LT;&的TModel GT; 。剃刀HTML编辑器很聪明,知道提前什么类型的tModel会根据你所说的这个观点的模型类型是时间。这就是为什么你有那么多的智能感知。

First, let's take a look at @Html. We know @ begins our Razor syntax and then Html is magic. Actually, Html is an HtmlHelper object that is automatically initialised and given to you. More specifically it's an HtmlHelper<TModel>. The Razor HTML editor is smart and knows ahead of time what type TModel will be based on what you've said this view's model type is. That's why you have so much intellisense.

当你键入

@model IEnumerable<BusinessLayer.Employee>

该编辑器读取并使得假设现在的HTML辅助将的HtmlHelper&LT;&IEnumerable的LT; BusinessLayer.Employee&GT;&GT; 。当谈到时间来编译页面的HTML辅助实际上将这种类型的(当然)。

The editor reads that and makes an assumption now that the HTML Helper will be HtmlHelper<IEnumerable<BusinessLayer.Employee>>. When it comes time to compile the page, the HTML helper will in fact be that type (of course).

那么,关于 DropDownListFor 或任何其他扩展方法?

So what about DropDownListFor or any other extension method?

看着 DropDownListFor 我们可以看到,它实际上 DropDownListFor&LT;的TModel,TProperty&GT; 。我们现在明白了的TModel是我们认为的型号。 DropDownListFor 知道这一点,因为该方法的延长 的HtmlHelper&LT;的TModel&GT; 。因此DropDownListFor知道传入类型是任何类型的视图的顶部被定义。什么 TProperty

Looking at DropDownListFor we can see that it's actually DropDownListFor<TModel, TProperty>. We now understand that TModel is our view's model type. DropDownListFor knows about this because the method is extending HtmlHelper<TModel>. Therefore DropDownListFor knows that the incoming type is whatever type is defined at the top of the view. What about TProperty?

TProperty 是返回类型。这是您在选择你的财产指定类型。该视图提供的HtmlHelper模型类型,那么谁给DropDownListFor模型类型,现在您在一个lambda前pression是:(X =&GT; x.Property)您选择哪个然后选择类型为你的财产;在这种情况下的字符串(性别)。

TProperty is the return type. That's the type that you specify when you select your property. The view gives HtmlHelper the model type, who then gives DropDownListFor the model type and now that you're in a lambda expression: (x => x.Property) you select the property which then selects the type for you; in this case a string (Gender).

这是很难回答你的问题不知道你想实现什么。你有没有员工的集合,你想显示每个多个性别下拉框,然后保存?

It's hard to answer your question without knowing exactly what you're trying to achieve. Do you have a collection of Employees and you want to display multiple gender dropdown boxes for each and then save them?

在与集合处理它有点更靠谱,因为MVC不处理得很好开箱即用;它通常是最好的根据是什么,你需要做写你自己的解决方案。

When dealing with collections it's a little more tricky, since MVC doesn't handle them well out of the box; it's usually best to write your own solutions according to what you need done.

我真的不喜欢让事物的集合页面上的单一视图的想法。考虑这块逻辑:

I don't really like the idea of a single view getting a collection of things on a page. Consider this piece of logic:


  • 让员工集合

  • 给员工一个视图

  • 有视图中创建一个单一的SelectListItem

  • 循环并显示每个员工选择列表


  • 让员工集合

  • 给员工一个视图

  • 必须通过视图循环,每个员工传递给其他图(局部)

  • 与单个员工
  • 每个部分交易
  • Get collection of Employees
  • Give employees to a view
  • Have the view loop through and pass each Employee to another view (partial)
  • Each partial deals with a single Employee

使用MVC不要试图打破的东西分解成小的,逻辑部分。意见应是愚蠢的;这意味着他们不应该真正做任何的逻辑和思维。事情变成这个样子更简单,它可以确保你的意见不长成怪物。

With MVC do try to break things down into small, logical parts. Views should be stupid; meaning they shouldn't really do any logic or thinking. Things become easier this way and it makes sure that your views don't grow into monsters.

试试这个:

创建一个新的名为PartialView _ EmployeeGender.cshtml 的同一个文件夹,你正在使用的视图。

Create a new PartialView called _EmployeeGender.cshtml in the same folder as the view you're using.

使用此code

_EmployeeGender.cshtml

@model BusinessLayer.Employee

<tr>
    <td>
    @{

        var listItems = new List<SelectListItem>()
        {
            new SelectListItem {Text = "Male",   Value = "M"},
            new SelectListItem {Text = "Female", Value = "F"}
        };

        @Html.DropDownListFor(m => m.Gender, listItems, string.Empty)
    }  

    </td>
</tr>

您的原始视图

@model IEnumerable<BusinessLayer.Employee>
@{
    ViewBag.Title = "Employees";
}

<h2>Employees</h2>

<table>
    @foreach (var employee in Model) 
    {
        Html.RenderPartial("_EmployeeGender", employee);
    }
</table>

结果

让我们来看看我们的生成的HTML 现在

<table>
<tr>
    <td>
<select id="Gender" name="Gender"><option value=""></option>
<option selected="selected" value="M">Male</option>
<option value="F">Female</option>
</select>  

    </td>
</tr><tr>
    <td>
<select id="Gender" name="Gender"><option value=""></option>
<option value="M">Male</option>
<option selected="selected" value="F">Female</option>
</select>  

    </td>
</tr></table>

我们可以看到,现在有一个空白的选择,我们的下拉框会自动与员工的价值观(我创建一个男性和一个女性雇员)。

We can see that there is now a blank selection and that our dropdown boxes are automatically selected with the Employee's values (I create one male and one female employee).

待办事项 ID 名称 HTML属性是相同的。如果你想提交一个表单使用这些值那么它将需要更多的工作。但是,这对你是一个合理的起点。

Do Note that the id and name HTML attributes are the same. If you want to submit a form with these values then it will require more work. But this is a reasonable starting point for you.

这篇关于@ Html.DropDownListFor基本用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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