Learning ASP. net mvc (7) -- my first ASP. net mvc query page, asp. netmvc

Source: Internet
Author: User
Tags asp net actionlink

Learning ASP. net mvc (7) -- my first ASP. net mvc query page, asp. netmvc

In this article, I will add a new query page (SearchIndex) that can be queried Based on the type or name of the book. The URL of this new page is http: // localhost: 36878/Book/SearchIndex. This page uses a drop-down box to display types. You can enter the name of a book in a text box. After a user clicks the "query" button, the page is refreshed to display the user's query results. The Controller parses the parameter values submitted by the user by Action Motehd and uses these values to query the database.

Step 1: Create a SearchIndex query page
First, add a SearchIndex Action Method to BookController. This method returns a view containing an HTML form. The Code is as follows:

public ActionResult SearchIndex(string searchString)
        {

           var books = from m in db.Books
                        select m;

           if (!String.IsNullOrEmpty(searchString))
           {

                books = books.Where(s => s.Name.Contains(searchString));

            }
            return View(books);
        }

The first line in the above SearchIndex method code is shown below. Its function is to create a LINQ query to filter the corresponding book data from the database:

       var books = from m in db.Books
                       select m;

This statement indicates that the query has been created, but data in the data storage area has not been filtered.
If the "searchString" parameter variable contains a string, the "books" query statement uses the value of the "searchString" parameter variable as the query condition to filter the corresponding book data, as shown in the following code:

 if (!String.IsNullOrEmpty(searchString))
            {
               books = books.Where(s => s.Name.Contains(searchString));

            }

In the code above, the s => s. Title code is a Lambda expression. Lambda expressions are used in method-based LINQ queries as parameters for standard query operator methods such as Where and Where. For example, the method used in the above Code. Their definitions are not executed during a LINQ query, or they are modified when a method is called or sorted. On the contrary, the query execution delay means that the calculation of an expression is delayed until the actual iteration of its variable ends or the method that can be called (ToList method) is called. On the SearchIndex page, the query is executed in the SearchIndex view.

Next, we will create a SearchIndex view to present this query interface to users. Right-click the SearchIndex method in the BookController file in Visual Studio, and click the "add view" menu in the pop-up menu. In the add view dialog box, specify that you want to pass a Book object to the view template as its model class. In the stent template list, select the list and click Add ". For example.


Click the Add button to create a view template for Views \ Book \ SearchIndex. cshtml. Because you have selected the list of supported templates in the list, Visual Studio automatically generates some default labels in the (built) view. Create an HTML form for the base frame. It checks the Book class and the created code to present each <label> element of the class. The following list shows the created View:

@model IEnumerable<MvcApplication1.Models.Book>
[H]
Viewbag. Title = "book query";
}
<h2>Book Search</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Category)
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Numberofcopies)
</th>
<th>
@Html.DisplayNameFor(model => model.AuthorID)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th>
@Html.DisplayNameFor(model => model.PublishDate)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Category)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Numberofcopies)
</td>
<td>
@Html.DisplayFor(modelItem => item.AuthorID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.PublishDate)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.BookID }) |
@Html.ActionLink("Details", "Details", new { id=item.BookID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.BookID })
</td>
</tr>
}
</table>
Press F5 to run the application and navigate to / book / searchindex using your browser. A query string will be appended to the URL, such as "? Searchstring = SQL". After submission, the eligible book data will be displayed. For example.
Third, modify the search index query method
We can also modify the parameters of the searchindex method, passing in a named parameter "Id", which will match the {ID} placeholder in the default routing settings in the global.asax file. The routing settings are as follows:
{controller}/{action}/{id}
The original searchindex method is as follows:
public ActionResult SearchIndex(string searchString)
{
var books = from m in db.Books
Select m;
if (!String.IsNullOrEmpty(searchString))
{
books = books.Where(s => s.Name.Contains(searchString));
}
return View(books);
}
The modified searchindex method will look like this:
public ActionResult SearchIndex(string id)
{
string searchString = id;
var books = from m in db.Books
Select m;
if (!String.IsNullOrEmpty(searchString))
{
books = books.Where(s => s.Name.Contains(searchString));
}
return View(books);
}
Now, you can use the query condition "book name" as routing data (a character in the URL), not as a query string value. For example.
Third, add "book name" query criteria
Through the above learning, we have realized the data query function. But we can't expect ordinary users to add query criteria in the URL just like us. When you need to query, modify the content of the query criteria in the URL to query books. Therefore, it is necessary to add a query page to facilitate ordinary users to input corresponding query conditions and query books according to the query conditions.
1、 Change the signature of the searchindex method, and bind it to the ID parameter by routing. Let the searchindex method accept a string named "searchstring" as the parameter. The code is as follows:
public ActionResult SearchIndex(string searchString)
{
var books = from m in db.Books
Select m;
if (!String.IsNullOrEmpty(searchString))
{
books = books.Where(s => s.Name.Contains(searchString));
}
return View(books);
}
2、 Open the views \ book \ searchindex.cshtml file, and add a text box and a query button at the location of @ html.actionlink ("create new", "create"). The contents are as follows:
@using (Html.BeginForm())
{
<p>Book Name: @ HTML. Textbox ("searchstring") < br / >
< input type = "submit" value = "query" / ></p>
}
The following code shows part of the views \ book \ searchindex.cshtml file with the added filter tags.
@Model IEnumerable<MvcApplication1.Models.Book>
[H]
Viewbag. Title = "book query";
}
<h2>Book Search</h2>
@using (Html.BeginForm())
{
<p>Book Name: @ HTML. Textbox ("searchstring") < br / >
< input type = "submit" value = "query" / ></p>
}
This HTML. Beginform helper creates a < form > tag. When the user submits the form by clicking the "query" button, the html.beginform helper method will submit the contents of the form to the controller and refresh the page at the same time.

3、 Press F5, run the application, enter "SQL" in the "book name" text box, and then click the "query" button to query the book. For example. There are also methods that do not need to overload httppost for searchindex. Because this method does not change the state of the application, it is only used to query data.
You can add [httppost] to the top of the searchindex method as follows. After adding [httppost], the browser will first call the searchindex method that matches httppost. The result of httppost's searchindex method is as follows.
[HttpPost]
public string SearchIndex(FormCollection fc, string searchString)
{
return "<h3> From [HttpPost]SearchIndex: " + searchString + "</h3>";
}
However, even if the httppost version of searchindex is added. Suppose the following scenario: you want to send a query result to your friends, and you want to send only a specific link to your friends so that they can query and view the same query result. Note that if it is the same query result, one is an HTTP post request and the other is the same URL get request (for example, local host: xxxxx / book / searchindex). The HTTP post request cannot see the query results without query parameters in the URL itself. If it's just a URL, it means that you and your friends will never see the same query results.
You should use the following solution, using the overloaded method of beginfo, to specify the corresponding query parameter information that the post request should add to the URL, which should be routed to the HTTP get version of the searchindex method. Replace the beginform method of the existing parameter with the following code: for example.
@using (Html.BeginForm("SearchIndex", "book", FormMethod.Get))
Now, when you click the "query" button, the URL will contain a string of query criteria. The query request will also request the searchindex operation method of HTTP get, even if you have a searchindex method of httppost. For example.
Third, add "book type" query method
The first step is to remove the searchindex method from the httppost version of the code.
The second step is to add a new query function. Add a query condition of "book type" to the page, so that users can query related books through "book type". Replace the searchindex method with the following code:
public ActionResult SearchIndex(string Category, string searchString)
{
var cateLst = new List<string>();
var cateQry = from d in db.Books
orderby d.Category
select d.Category;
cateLst.AddRange(cateQry.Distinct());
ViewBag.category = new SelectList(cateLst);
var books = from m in db.Books
Select m;
if (!String.IsNullOrEmpty(searchString))
{
books = books.Where(s => s.Name.Contains(searchString));
}
if (string.IsNullOrEmpty(Category))
return View(books);
Else
{
return View(books.Where(x => x.Category == Category));
}
}
This new searchindex method adds a new query condition, category. The first few lines of the code create a list object to query "Book types" from the database and add the results of the query to the list object.
The following code is a LINQ query from the database to find out all kinds of books.
var cateQry = from d in db.Books
orderby d.Category
select d.Category;
The following code is used to add all book types to the list using the addrange method of the generic list collection. (without the distinct modifier, the same type will be added to the list - for example, MS, SAP will be added twice).
cateLst.AddRange(cateQry.Distinct());
The code is then stored in the viewbag object genre list.
ViewBag.category = new SelectList(cateLst);
The following code shows how to check the category parameter. If it is not empty, the code further limits the selection of books for book query to the specified category.
if (string.IsNullOrEmpty(Category))
return View(books);
Else
{
return View(books.Where(x => x.Category == Category));
}
Fourth, add "book type" query criteria in the search index query page
Add an HTML style dropdownlist to the views \ book \ searchindex.cshtml file, ahead of the book name text box. The completed code is as follows:
<p>
@using (Html.BeginForm("SearchIndex","book",FormMethod.Get)){
<p>Book type: @ HTML. Dropdownlist ("category", "all")
Book Name: @ HTML. Textbox ("searchstring")
< input type = "submit" value = "query" / ></p>
}
</p>
Press F5 to run the application and browse the / book / searchindex address in the browser. You can query book information by "book type" and "book name". For example, 1, figure 2.
In this article, learn how to create a new query operation method and view to let users query by book name and book type.
Get to know MVC, teach and point out a way to learn aspnet mvc3 or an in-depth learning method
Go to MSDN to understand the operation mode of MVC. Download a simple case. Follow along. If you don't say that you are proficient, at least you can master the most basic
The problem of asp net mvc3 passing values to the page through JS, and then to the page, and the background value problem
You can input the address of landmark / createlandmark? Projectid = 1 directly in the browser to see if you can get the value

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.