【问题标题】:MVC Search in a non-IEnumerable Model非 IEnumerable 模型中的 MVC 搜索
【发布时间】:2015-04-21 17:56:51
【问题描述】:

我有一个适用于 IEnumerable 模型的搜索方法。

如何使其与简单模型一起使用? (或者怎么称呼..)

控制器:

 [HttpPost] //FOR SEARCH (WORKING)
    public ActionResult Search(string searchNume)
    {
        List<Contact> contactsList;
        if (string.IsNullOrEmpty(searchNume))
        {
            contactsList = db.Contacts.ToList();
        }
        else
        {
            contactsList = db.Contacts.Where(x => x.Nume.Contains(searchNume)).ToList();
        }
        return View(contactsList);
    }

查看:

@using Demo.Model.Contact
    @using (Html.BeginForm())
    {
        <th>
            @Html.TextBoxFor(model => model.Nume)
        </th>
        <th>
            @Html.TextBoxFor(model => model.Prenume)
        </th>
        <th>
            @Html.TextBoxFor(model => model.Adresa)
        </th>
        <th>
            @Html.TextBoxFor(model => model.Mentiuni)
        </th>
        <th>
            <input type="submit" name="submitSearch" value="Search" class="btn btn-info"
                   onclick=" location.href='@Url.Action("Search", "Home")' " />
        </th>

UPDATE1:将 Index ActionResult 更改为 Search

UPDATE2:发布更多索引视图

Update3:更改后重新发布代码

        ////Search GET
    //[ChildActionOnly]
    public PartialViewResult Search() // for displaying the initial view with all contacts
    {
        List<Contact> contactsList = db.Contacts.ToList();
        return PartialView("Contacts", contactsList);
    }

    ////Search POST
    [HttpPost]
    public PartialViewResult Search(string txtsearchNume)
    {
        List<Contact> contactsList;
        if (string.IsNullOrEmpty(txtsearchNume))
        {
            contactsList = db.Contacts.ToList();
        }
        else
        {
            contactsList = db.Contacts.Where(x => x.Nume.Contains(txtsearchNume)).ToList();
        }
        return PartialView("Contacts", contactsList);
    }

查看:

    @using Demo.Models
    @model Contact

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@section scripts
{
    <link href="~/Content/jquery-ui.min.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-ui.min.js"></script>
    <script src="~/Scripts/jquery-ui.js"></script>    
    <script>            

            //Search
            var url = '@Url.Action("Search", "Home")';
            var filter = $('#Nume');
            var results = $('#results');
            $('#search').click(function () {
                results.load(url, { txtsearchNume: filter.val() });
            });    

        });
    </script>
}    

        @using (Html.BeginForm())
        {       
                @Html.TextBoxFor(model => model.Nume, null, new { id = "txtSearchNume", @class = "form-control" })

                <button type="button" id="search">Search by Nume</button>
           }

<div id="results">
    @Html.Action("Search")  
</div>

【问题讨论】:

  • 不清楚你在问什么。您为Index() 方法显示的视图是否(在这种情况下它不起作用)?您在onclick 事件中引用的Search 方法是什么,并且由于您没有将任何参数传递给该方法,您期望得到什么结果?
  • 你想用 Ajax(异步)搜索调用填充(重新加载)某种网格吗?
  • 我正在搜索一个表,当我为该视图使用 Ienumerable 模型时,此方法曾经有效。我需要将模型更改为简单,现在我还必须更改控制器操作,因为它说模型列表不可分配给模型类型 Demo.Models。我期待来自数据库表项的匹配项列表。我会用完整的索引视图更新问题,所以我猜你可以看得更好。
  • 如果你想要一个标准的提交,然后将方法设为 GET(不是帖子)并包含一个带有文本框 (name="searchNume") 的表单 (FormMethod.Get) 和提交按钮,这样你就可以通过将文本框的值传递给 Index() 方法,否则将 ajax 用于返回带有结果的部分视图并更新 DOM 的方法。
  • 你想在这里做什么。为什么提交按钮中有onclick=" location.href='@Url.Action("Search", "Home")?如果不会将任何内容传递给 Search() 方法。如果您删除它,您将回发一个 Contact 类型的模型,但该方法需要参数 string searchNume 您的查询建议您要按属性搜索 Nume 那么其他 3 个文本框的意义何在?

标签: c# asp.net-mvc


【解决方案1】:

您的表单提交按钮有onclick="location.href='@Url.Action("Search", "Home")'",它重定向到GET 方法并且不传递任何参数。您的Search() 方法被标记为[HttpPost] 并需要一个名为searchNume 的参数,因此您的onclick() 事件实际上并没有做任何事情。根据您的 cmets,您可以使用 jquery 处理此问题(此示例假设您只想按属性 Nume 进行搜索,如 Search() 方法中所示)

Html(将&lt;input type="submit" ..&gt; 替换为)

<button type="button" id="search">Search by Nume</button>

<div id="results">
    @Html.Action("Search") // to initially display all contacts
</div> // place holder for the search results

并添加以下脚本

var url = '@Url.Action("Search", "Home")';
var filter = $('#Nume');
var results = $('#results');
$('#search).click(function() {
  results.load(url, { searchNume: filter.val() });
});

并修改控制器方法以返回包含过滤后联系人的部分视图

public PartialViewResult Search() // for displaying the initial view with all contacts
{
    List<Contact> contactsList = db.Contacts.ToList();
    return PartialView("_Contacts", contactsList);
}

[HttpPost]
public PartialViewResult Search(string searchNume)
{
    // could make this IEnumerable<Contact> and avoid the extra overhead of .ToList()?
    List<Contact> contactsList; 
    if (string.IsNullOrEmpty(searchNume))
    {
        contactsList = db.Contacts.ToList();
    }
    else
    {
        contactsList = db.Contacts.Where(x => x.Nume.Contains(searchNume)).ToList();
    }
    return PartialView("_Contacts", contactsList); // partial view
}

您的部分视图 (_Contacts.cshtml) 可能看起来像(来自您的 previous question

@model IEnumerable<Demo.Models.Contact>
<table class="table table-bordered table-hover">
    @foreach (var item in Model)
    {
        <tr>
            <td>@Html.DisplayFor(modelItem => item.ContactId)</td>
            <td>@Html.DisplayFor(modelItem => item.Nume)</td>
            ....
        </tr>
    }
</table>

旁注:如果您的初始视图显示所有联系人,那么您可以通过使用 javascript/jquery 在客户端过滤列表来提高性能并避免调用控制器。网上有很多例子including this one

【讨论】:

  • 在控制器 'Demo.Controllers.HomeController' 上找不到公共操作方法 'Search'。第 137 行:@Html.Action("Search") 也许你知道如何比我更好地调试它.我认为@html.Action 需要另一种类型的控制器,而不是 PartialViewResult
  • 我假设Search() 方法在同一个控制器中。您只需要指定控制器名称,因此假设它在 ContactController 中,那么它将是 @Html.Action("Search", "Contact")
  • 一切都在家庭控制器中。即使我指定 @Html.Action("Search", "Home"),我也会收到相同的错误
  • 糟糕。抱歉,我忘了添加 GET 方法 - 稍后会更新。
  • 斯蒂芬你还在吗?
【解决方案2】:

如果您要在 Contact 实体上搜索多个属性,则需要一个单独的搜索模型。

// model
public class ContactSearchModel
{
    public string Nume { get; set; }
    public string Prenume { get; set; }
    public string Adresa { get; set; }
    public string Mentiuni { get; set; }
}

// view
@using Demo.Model.ContactSearchModel
@using (Html.BeginForm())
{
    <th>
        @Html.TextBoxFor(model => model.Nume)
    </th>
    <th>
        @Html.TextBoxFor(model => model.Prenume)
    </th>
    <th>
        @Html.TextBoxFor(model => model.Adresa)
    </th>
    <th>
        @Html.TextBoxFor(model => model.Mentiuni)
    </th>
    <th>
        <input type="submit" name="submitSearch" value="Search" class="btn btn-info"
               onclick=" location.href='@Url.Action("Search", "Home")' " />
    </th>

这就是你使用它的方式:

// controller
[HttpPost] //FOR SEARCH (WORKING)
public ActionResult Search(ContactSearchModel search)
{
    List<Contact> contactsList;
    if (search != null)
    {
        var query = db.Contacts.AsQueryable();

        if(!string.IsNullOrEmpty(search.Nume))
            query = query.Where(x => x.Nume.Contains(search.Nume));
        if(!string.IsNullOrEmpty(search.Prenume))
            query = query.Where(x => x.Prenume.Contains(search.Prenume));
        if(!string.IsNullOrEmpty(search.Adresa))
            query = query.Where(x => x.Adresa.Contains(search.Adresa));
        if(!string.IsNullOrEmpty(search.Mentiuni))
            query = query.Where(x => x.Mentiuni.Contains(search.Mentiuni));

        contactsList = query.ToList();
    }
    else
    {
        contactsList = db.Contacts.ToList();
    }
    return View(contactsList);
}

【讨论】:

  • 我不明白这是怎么回事。也许你不明白我的问题。无论如何,Multumesc:p
  • 告诉我你想在页面上做什么(必要时用罗马尼亚语),我会帮你做的。
  • @ Radu Porumb 我有一个由 2 个表(Contact 和 ContactTelefon)组成的数据库,它们都有共同的 ContactId 字段。我从表中制作了一个 ADO 模型,并有 2 个与表同名的类。我需要制作一个包含 4 个文本框的表格,这些文本框可以处理搜索/创建以及每行的编辑/删除。就用户而言,所有这些都必须发生在同一个视图上。这是我发布大部分代码的另一个问题的链接:stackoverflow.com/questions/29614255/…。 Multumesc pentru 调节器 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 2011-12-07
  • 2019-09-10
  • 2011-11-20
相关资源
最近更新 更多