最初插入空行到选择列表中的MVC LINQ SQL [英] Insert initial blank row into select list MVC LINQ SQL

查看:104
本文介绍了最初插入空行到选择列表中的MVC LINQ SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code,它是我formViewModel要传递给我的看法。

I have the following code that is in my formViewModel to be passed to my View.

        var ownerValues = aspnet_Users
            .OrderBy(u => u.Surname)
            .Select(u => new KeyValuePair<int, string>(u.UserId, u.Surname + " " + u.Forename.ToString() + " [" + u.UserName.ToString() + "]"));
        this.OwnersList = new SelectList(ownerValues, "Key", "Value", incidentAction.OwnerId);

当我运行在资源管理器视图我的下拉列表默认为第一个项目,我希望它默认为一个空行。

When I run the view in explorer my drop list defaults to the first item and I want it to default to a blank row.

所以我的计划是要插入一个初始行与用户id =空,然后一个空字符串,而不是'请选择'或类似的东西。

So my plan is to insert a initial row with userId = null and then an empty string instead of 'please select' or something similar.

任何人都可以请告诉我如何做到这一点的code我想,不知道从哪里开始。

Can anyone please advise me on how to do this on one line of code I think, not sure where to start.

感谢

推荐答案

当你渲染你的SelectList可以这样做

When Rendering your SelectList you can do something like

<%:Html.DropDownListFor(x => x.ApprovalType, Model.ApprovalTypes,"")%>

如果你想强类型列表,或者你可以尝试

if you want strongly typed list or you can try

<%:Html.DropDownList("ApprovalType", Model.ApprovalTypes, "") %>

在这两个例子中Model.ApprovalTypes包含的SelectList或SelectListItems列表。在结束空字符串参数是可选的标签,其价值也是一个空字符串结果
修改当您试图用数据注释来验证它的一些值插入标签(空字符串或者别的什么)也将产生问题。选择空标签不会触发错误消息,因为联想的价值将是-1(不为空),如其他答案建议。

in both examples Model.ApprovalTypes contains a SelectList or List of SelectListItems. Empty string parameter at the end is optional label and its value is also an empty string
Edit Inserting label (empty string or something else) with some value will also create problems when you try to validate it using data annotations. Selecting empty label will not trigger the error message because associate value will be -1 (not empty) as suggested in other answer.

这篇关于最初插入空行到选择列表中的MVC LINQ SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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