1

我正在使用 asp.net mvc4、simplemembership 和 EF。

实际上我有这个代码来搜索我的数据库中的用户。

家庭控制器:

        private UsersContext db = new UsersContext();

        public ActionResult Index(string searchUser)
        {
            var user = from m in db.UserProfiles
                       select m;

            if (!String.IsNullOrEmpty(searchUser))
            {
                user = user.Where(s => s.UserName.Contains(searchUser));
            }

            return View(user);
        }

索引视图:

 <div id="searchUser">
            @using (Html.BeginForm("Index", "Home", FormMethod.Get))
            {   
                <p>
                    @Html.TextBox("searchUser")
                    <input type="submit" value="Chercher" />
                </p>     
            }
  </div>
             /********** PART 1 ***********/
        @{
            var db = new UsersContext();
            var list = db.UserProfiles.ToList();

            foreach (var item in list)
            {
                <table>
                    <tr>
                        <td>
                            @Html.DisplayFor(m => item.UserName)
                        </td>
                    </tr>
                </table>

            }
        }

这里的第 1 部分已过时。而不是它,如果他存在,我想返回我搜索的用户的名称,否则我想显示一条消息说他不存在。

实际上,我的请求似乎有效,但视图中没有返回任何内容,有人知道我该如何解决这个问题吗?

谢谢你。

4

1 回答 1

2

试试这样的,

在你的控制器上,你总是应该为你的视图返回相同的类型。

private UsersContext db = new UsersContext();

public ActionResult Index(string searchUser = "")
{
    IEnumerable<User> result;

    if (!String.IsNullOrEmpty(searchUser))
    {
        var userFound = (from m in db.UserProfiles
                   where m.UserName.Constains(searchUser)
                   select m).FirstOrDefault(); // to take the first user you have found, but it is still an List.

            result = new List<User>() { userFound };
    }
    else 
    {
        result = (from m in db.UserProfiles
                 select m).ToList();
    }

    return View(result); // return the type for your view
}

并在 Action 上键入相同类型的视图并阅读它以显示表格...

// type your view with IEnumerable<User>
@model IEnumerable<User>

<div id="searchUserForm">
    @using (Html.BeginForm("Index", "Home", FormMethod.Get))
    {   
    <p>
        @Html.TextBox("searchUser")
        <input type="submit" value="Chercher" />
    </p>     
    }
</div>

@if (Model.Any()) // Model is an IEnumerable<User>
{
    <table>
        <tr>
            <th>UserName</th>
        </tr>   
    foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(m => item.UserName)
            </td>
        </tr>
    }
    </table>
}
else 
{
    <p> No users to display.</p>
}
于 2012-12-18T20:00:05.507 回答