ASP.NET MVC 3 用户下拉列表

发布于 2025-01-08 07:00:55 字数 1389 浏览 0 评论 0原文

在我的应用程序中,我已将我的 UserId 关联到数据库中的一个表。我需要在创建新项目时可以从下拉列表中选择用户名。 '可以用元素 viewbag 来做到这一点吗?

@Html.EditorFor(model => model.UserId)

我使用默认的成员资格提供程序,因此无法使用实体框架来解决此问题

编辑

编辑2

这是我的操作创建:

[HttpPost]
public ActionResult Create(Employe employe)
{
        var users = Roles.GetUsersInRole("Admin");
        SelectList list = new SelectList(users);
        ViewBag.Users = list;
        if (ModelState.IsValid)
        {
            **employe.EmployeID = users;**
            db.Employes.Add(employe);
            db.SaveChanges();
}

这不起作用。错误是:

无法将类型“string[]”隐式转换为“string”

我的 Employee

public class Employee
{
        [Key]
        public int EmployeID { get; set; }

        public Guid UserId { get; set; }

        public string Name { get; set; }

        [ForeignKey("UserId")]
        public virtual MembershipUser User
        {
            get
            {
                return Membership.GetUser(this.Name); //Changed this to Name 
            }
        }

    }
}

视图模型:

@Html.DropDownList("Users", ViewBag.Users as SelectList);

UserId 字段中的结果不是 UserId但是这个000000-000000-0000000-00000

In my application I have associated my UserId to a table in my database. I need that when I create a new item I can choose the user name from a dropdownlist. And 'possible to do this with the element viewbag?

@Html.EditorFor(model => model.UserId)

I use default membership provider so I can't use Entity Framework for this problem

EDIT

EDIT 2

This is my action create:

[HttpPost]
public ActionResult Create(Employe employe)
{
        var users = Roles.GetUsersInRole("Admin");
        SelectList list = new SelectList(users);
        ViewBag.Users = list;
        if (ModelState.IsValid)
        {
            **employe.EmployeID = users;**
            db.Employes.Add(employe);
            db.SaveChanges();
}

This does not work. The error is:

Cannot implicitly convert type 'string[]' to 'string'

My model for Employee

public class Employee
{
        [Key]
        public int EmployeID { get; set; }

        public Guid UserId { get; set; }

        public string Name { get; set; }

        [ForeignKey("UserId")]
        public virtual MembershipUser User
        {
            get
            {
                return Membership.GetUser(this.Name); //Changed this to Name 
            }
        }

    }
}

View:

@Html.DropDownList("Users", ViewBag.Users as SelectList);

My result in UserId field isn't a UserId but this 000000-000000-0000000-00000

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

东京女 2025-01-15 07:00:55

如何将用户列表设置为 ViewBack 中的 SelectItem
是的,您应该能够通过将集合传递到 ViewBag,然后从中创建下拉菜单来完成此操作:

在您的控制器中

        var users = Roles.GetUsersInRole("Admin");
        SelectList list = new SelectList(users);
        ViewBag.Users = list;

在您的视图中(如果您使用的是 Razor)

@Html.DropDownList("Users", ViewBag.Users as SelectList);

在此处阅读有关 SelectListItem 的更多信息:

另请查看:

问题变成了更多问题。这是我解决问题的想法:

控制器

public ActionResult Mirko() {
    List<SelectListItem> items = new List<SelectListItem>();    
    foreach (string userName in Roles.GetUsersInRole("Admin")) {
        var user = Membership.GetUser(userName);
        SelectListItem li = new SelectListItem {
            Value = user.ProviderUserKey.ToString(),
            Text = user.UserName,
        };
        items.Add(li);
    }
    items.Add(new SelectListItem { Text = "Please Select...", Value = "na" , Selected = true});
    ViewBag.Users = items;
    return View();                
}

[HttpPost]
public ActionResult Mirko(Employee employee) {
    if(IsValideEmployee(employee)) {
        /*Only used to show that user was retrieved*/
        TempData["message"] = "Saved Employee";
        TempData["user"] = employee.User;

       /* employeeRepository.Save(employee) */

        /* Redirect to where you want to go */
        return RedirectToAction("Mirko", "Home");
    }
    return View(employee);
}

private bool IsValideEmployee(Employee emp) {
    if (emp.Name == "na")
        ModelState.AddModelError("UserId", "You must select a user!");
    /*Do some validation here*/
    //ModelState.Add("Name", "You must set the user name!")
    return ModelState.IsValid;
}

视图

@model StackOverFlowExample.Models.Employee
@{
    MembershipUser user = null;
    ViewBag.Title = "Mirko Example";
    var users = ViewBag.Users as IEnumerable<SelectListItem>;
}

@if (TempData["message"] != null) {
    user = TempData["user"] as MembershipUser;
    <h3>@TempData["message"]</h3>
    <div>
        <span>You selected @user.UserName</span>
        <ul>
            <li>Email: @user.Email</li>
            <li>Last Logged In: @user.LastLoginDate.ToString("d")</li>
            <li>Online: @user.IsOnline</li>
        </ul>
    </div>
}

@using (@Html.BeginForm()) { 
    <label for="UserId">Associate Employee To User:</label>
    @Html.DropDownListFor(m => m.UserId, @users)
    @Html.HiddenFor(m => m.Name)                                               
    <input type="submit" value="Save" id="save-employee"/>
}
<div id="status" style="display:none;"></div>

<script type="text/javascript">
    $(document).ready(function () {
        $("#UserId").change(function () {
            //Set value of name 
            $("#Name").val($(this).children("option:selected").text());            
        });
        $("#save-employee").click(function (e) {
            var value = $("#Name").val();
            if (value == "" || value == "na") {
                e.preventDefault();
                $("#status").html("<h3>You must select a user!</h3>").toggle();
            }
        });
    });
</script>

How to set a list of users as a SelectItem in the ViewBack
Yes, you should be able to do this by passing your collection to the ViewBag and then create you dropdown from it:

In your controller

        var users = Roles.GetUsersInRole("Admin");
        SelectList list = new SelectList(users);
        ViewBag.Users = list;

In your View (If you're using Razor)

@Html.DropDownList("Users", ViewBag.Users as SelectList);

Read more about SelectListItem here:

Also check out:

Question changed to something more. Here is my idea to solve the issue:

Controller:

public ActionResult Mirko() {
    List<SelectListItem> items = new List<SelectListItem>();    
    foreach (string userName in Roles.GetUsersInRole("Admin")) {
        var user = Membership.GetUser(userName);
        SelectListItem li = new SelectListItem {
            Value = user.ProviderUserKey.ToString(),
            Text = user.UserName,
        };
        items.Add(li);
    }
    items.Add(new SelectListItem { Text = "Please Select...", Value = "na" , Selected = true});
    ViewBag.Users = items;
    return View();                
}

[HttpPost]
public ActionResult Mirko(Employee employee) {
    if(IsValideEmployee(employee)) {
        /*Only used to show that user was retrieved*/
        TempData["message"] = "Saved Employee";
        TempData["user"] = employee.User;

       /* employeeRepository.Save(employee) */

        /* Redirect to where you want to go */
        return RedirectToAction("Mirko", "Home");
    }
    return View(employee);
}

private bool IsValideEmployee(Employee emp) {
    if (emp.Name == "na")
        ModelState.AddModelError("UserId", "You must select a user!");
    /*Do some validation here*/
    //ModelState.Add("Name", "You must set the user name!")
    return ModelState.IsValid;
}

View

@model StackOverFlowExample.Models.Employee
@{
    MembershipUser user = null;
    ViewBag.Title = "Mirko Example";
    var users = ViewBag.Users as IEnumerable<SelectListItem>;
}

@if (TempData["message"] != null) {
    user = TempData["user"] as MembershipUser;
    <h3>@TempData["message"]</h3>
    <div>
        <span>You selected @user.UserName</span>
        <ul>
            <li>Email: @user.Email</li>
            <li>Last Logged In: @user.LastLoginDate.ToString("d")</li>
            <li>Online: @user.IsOnline</li>
        </ul>
    </div>
}

@using (@Html.BeginForm()) { 
    <label for="UserId">Associate Employee To User:</label>
    @Html.DropDownListFor(m => m.UserId, @users)
    @Html.HiddenFor(m => m.Name)                                               
    <input type="submit" value="Save" id="save-employee"/>
}
<div id="status" style="display:none;"></div>

<script type="text/javascript">
    $(document).ready(function () {
        $("#UserId").change(function () {
            //Set value of name 
            $("#Name").val($(this).children("option:selected").text());            
        });
        $("#save-employee").click(function (e) {
            var value = $("#Name").val();
            if (value == "" || value == "na") {
                e.preventDefault();
                $("#status").html("<h3>You must select a user!</h3>").toggle();
            }
        });
    });
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文