在Asp.net MVC中执行搜索

Pan*_*yay 9 c# search asp.net-mvc-3

我是Asp.net MVC的新手,不知道如何进行搜索.这是我的要求,请告诉我你将如何处理: -

我需要有文本框,用户可以在其中输入搜索查询或字符串.然后用户单击按钮或按Enter键提交.字符串需要与表的属性名称匹配.

注意: - 查询数据并获取结果不是重点.我需要知道的是,您将如何获取用户输入并将其传递给控制器​​操作或其他任何进一步处理.只需告诉我您将如何阅读用户输入以及将其发送到哪里进行搜索.

Mat*_*sca 10

Asp.Net MVC使用标准HTTP动词.对于html部分,它是一个指向url的普通html表单.在服务器端,该URL将被路由到控制器/动作,该控制器/动作将处理输入并执行所需操作.

我们有一个样本.您想要创建搜索表单.首先,让搜索表单使用HTTP GET方法而不是POST是最佳做法,因此搜索结果可以加入书签,链接,索引等.我不会使用Html.BeginForm帮助方法来做更多事情明确.

<form method="get" action="@Url.Action("MyAction", "MyController")">
<label for="search">Search</label>
<input type="text" name="search" id="search" />
<button type="submit">Perform search</button>
</form>
Run Code Online (Sandbox Code Playgroud)

这就是你需要的所有HTML.现在你将有一个名为"MyController"的控制器,方法将是这样的:

[HttpGet]
public ActionResult MyAction(string search)
{
//do whatever you need with the parameter, 
//like using it as parameter in Linq to Entities or Linq to Sql, etc. 
//Suppose your search result will be put in variable "result".
ViewData.Model = result;
return View();
}
Run Code Online (Sandbox Code Playgroud)

现在将呈现名为"MyAction"的视图,该视图的模型将成为您的"结果".然后你会按照自己的意愿展示它.


Dar*_*rov 8

与ASP.NET MVC应用程序一样,您首先要定义一个视图模型,该模型将表达视图的结构和要求.到目前为止,您已经讨论过包含搜索输入的表单:

public class SearchViewModel
{
    [DisplayName("search query *")]
    [Required]
    public string Query { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后你写一个控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new SearchViewModel());
    }

    [HttpPost]
    public ActionResult Index(SearchViewModel model)
    {
        if (!ModelState.IsValid)
        {
            // There was a validation error => redisplay the view so 
            // that the user can fix it
            return View(model);
        }

        // At this stage we know that the model is valid. The model.Query
        // property will contain whatever value the user entered in the input
        // So here you could search your datastore and return the results

        // You haven't explained under what form you need the results so 
        // depending on that you could add other property to the view model
        // which will store those results and populate it here

        return View(model);
    }
}
Run Code Online (Sandbox Code Playgroud)

最后一个观点:

@model SearchViewModel

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Query)
    @Html.EditorFor(x => x.Query)
    @Html.ValidationMessageFor(x => x.Query)
    <button type="submit">Search</button>
}
Run Code Online (Sandbox Code Playgroud)

  • @Pankaj Upadhyay,您仍然可以在表单上使用带有GET动词的视图模型.我认为你应该总是使用视图模型. (3认同)