使用DropDownListFor的MVC Postback数据 [英] MVC Postback data with DropDownListFor

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

问题描述

我对MVC(VS2012中的MVC4)很新,并且需要以下建议。

我正在使用实体框架。



我有一个视图,将显示所选的用户详细信息(标题,名字等等)。

在此下它将显示用户的爱好。

在用户的爱好下面有一个下拉列表框和旁边的添加按钮。

这个添加按钮将从下拉列表框中添加所选择的爱好。



我正在使用强类型视图。



我有一个问题,一旦我选择了一个爱好并点击了添加按钮我只会在控制器的AddHobby()部分中获得所选的业余爱好IDuserHobby.SelectedId,但userHobby.User将为null。我需要用户ID。

我使用隐藏的Htmlhelper@ Html.Hidden(userId,Model.User.Id)来检索用户ID。这很有效。



这两个问题是:

1)为什么我在userHobby.User中得到一个null?

2)有更好更清洁的方法吗?



这是代码:

用户和爱好模型

I'm very new to MVC (MVC4 in VS2012) and would need some advice on the following.
I'm using the Entity Framework.

I have a view that will display the selected user details (Title, first name, etc...).
Under that it will display the user's hobbies.
Under the user's hobbies there is a dropdown listbox and a add button next to it.
This add button will add the selected hobby from the dropdown listbox.

I'm using strongly typed View.

I had a problem that once I've selected a hobby and clicked the add button I would only get the selected hobby Id "userHobby.SelectedId", in the AddHobby() section in the controller, but the "userHobby.User" would be null. I need the user Id.
I resorted to use a hidden Htmlhelper "@Html.Hidden("userId", Model.User.Id)" to retrieve the user Id. This worked.

The two questions is:
1) Why am I getting a null in the "userHobby.User"?
2) Is there a better and a cleaner way of doing this?

This is the code:
The User and Hobby Model

public partial class User
{
    public User()
    {
        this.Hobbies = new HashSet<Hobby>();
    }

    public int Id { get; set; }
    public string title { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string emailAddress { get; set; }

    public virtual ICollection<Hobby> Hobbies { get; set; }
}

public partial class Hobby
{
    public Hobby()
    {
        this.Users = new HashSet<User>();
    }

    public int Id { get; set; }
    public string hobbyName { get; set; }
    public string hobbyType { get; set; }
    
    public virtual ICollection<User> Users { get; set; }

}

// This is the one that I pass through to the view as a strong typed.
public class ViewModelHobby
{
    public int SelectedId { get; set; }
    public User User { get; set; }

    public IEnumerable<Hobby> Hobbies { get; set; }

}





视图中的代码



The code in the View

@model Multiple_Lists.ViewModels.ViewModelHobby

@{
    ViewBag.Title = "User Details";
}

<h2>Details</h2>
@using (Html.BeginForm("AddHobby", "User", Model, FormMethod.Post))
{
<fieldset>
    <legend>User</legend>

    @Html.Hidden("userId", Model.User.Id)

    <div class="display-label">
         @Html.DisplayNameFor(model => model.User.title)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.User.title)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.User.firstName)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.User.firstName)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.User.lastName)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.User.lastName)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.User.emailAddress)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.User.emailAddress)
    </div>

    <table class="display-table">
        <thead>
            <tr>
                <th>Hobby Name</th>
                <th>Hobby Type</th>
                <th>Delete</th>

            </tr>

        </thead>

        <tbody>
            @foreach (var item in Model.User.Hobbies)
            {
                <tr>
                    <td>
                        @item.hobbyName
        
                    </td>

                    <td>
                        @item.hobbyType

                    </td>
    
                    <td>
                        @Html.ActionLink(" ", "DeleteHobby", "User", new { hobbyId = item.Id, userId = Model.User.Id}, new {  @class = "delete-pic" })

                    </td>

                </tr>

            }
            
        </tbody>

    </table>

    <div>
        @Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.Hobbies, "Id", "hobbyName"))

        <input type="submit" value="Add" />

    </div>

</fieldset>

}





控制器中的代码查看用户详细信息



The code in the controller to view the user details

public ActionResult Details(int userId = 0)
{
    ViewModelHobby userHobbies = new ViewModelHobby();

    User user = db.Users.Find(userId);
    List<Hobby> hobbies = db.Hobbies.ToList();

    userHobbies.User = user;
    userHobbies.Hobbies = hobbies;
    userHobbies.SelectedId = 0;

    return View(userHobbies);

}





控制器中用于将新选择的爱好插入用户的代码。



The code in the controller to insert the newly selected hobby to the user.

public ActionResult AddHobby(ViewModelHobby userHobby, int userId)
{
    // --------------------------------------------------------
    // Do database work to insert the new hobby for the user.
    // --------------------------------------------------------

    return RedirectToAction("Details", "User", new { userId = userId});

}

推荐答案

如果您不希望在添加每个和每个爱好时进行回发,您可以:

- 使用会话变量来存储已编辑用户的状态,并使用ajax调用添加爱好

- 使用多选列表框而不是下拉列表

- 使用数组来保留业余爱好列表并立即发布(参见我的文章:在ASP.NET MVC3中使用无阻碍验证的动态表格输入 [ ^ ])

请注意,所有爱好的列表都不是您的用户模型的一部分,它是您的域模型的一部分。如果你使用 userHobbies.Hobbies ,你会误导自己。您应该使用封装用户和相关域模型的viewmodel,或ViewData / ViewBag功能来传递其他数据,或者直接在视图中获取其他数据 - 因为这是一个表示问题。
If you don't want to do a postback on adding every and each hobby, you can either:
- use a session variable to store the edited user's state and add the hobbies with an ajax call
- use a multiselect listbox instead of dropdowns
- use a "array" to keep the hobby list and post at once (see my article: Dynamic tabular input with unobstructive validation in ASP.NET MVC3[^])
Be aware, that the list of all hobbies is not part of your user model, it is part of your domain model. You mislead yourself if you use userHobbies.Hobbies for that. You should either use a viewmodel that encapsulates the user and the related domain model, or the ViewData/ViewBag capability to pass the additional data, or get the additional data directly in the view - since that is a presentation concern.


这篇关于使用DropDownListFor的MVC Postback数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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