ASP. net mvc Case Study (4)

Source: Internet
Author: User

Preface

Through the previous articles, we have been able to easily use ASP. net mvc to present pages and data. However, there is a major problem that cannot be solved: how to process form data. For example, you must enter the title, body, and other content on a form page, and then submit the announcement, then the form data will be transferred to the corresponding place for processing by the business logic component.

In the traditional ASP. NET, the Model1 mode is used. Each aspx page has An aspx with the same name. cs file. When a form is submitted, the data is submitted to this aspx file with the same name by default. A Method in the cs file. However, in ASP. net mvc, this method cannot be used, because we use the Model2 mode instead, we cannot use code files with the same name to process aspx submission requests, but this does not indicate that the code files with the same name are useless. In fact, it will still be executed, but we do not advocate processing any logic in it, but sometimes it will be used for some initialization operations .), So what should we do? Let's explain the problem in examples.

Next we will step through the "MVC announcement publishing system" announcement publishing function. After this function is completed, the above problems will be clarified.

Create input information page

Next, we will officially start our work. First, I want to create a page for users to enter announcement information. We know that in ASP. net mvc cannot directly request the aspx file. Any request must pass through the Controller. Therefore, we first create a new Controller class named AnnounceController under the Controllers directory. Delete the automatically generated Index method and create an Action method named Release. The Code is as follows.

AnnounceController. cs:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MVCDemo.Models;
using MVCDemo.Models.Interfaces;
using MVCDemo.Models.Entities;
namespace MVCDemo.Controllers
{
public class AnnounceController : Controller
{
public ActionResult Release()
{
ICategoryService cServ = ServiceBuilder.BuildCategoryService();
List categories = cServ.GetAll();
ViewData["Categories"] = new SelectList(categories, "ID", "Name");
return View("Release");
}
}
}

This is the Action method to render a single page of a table. Let's see what it does: it first extracts all the categories, converts them to the SelectList type, stores them to ViewData, and finally presents the Release view.

Why do we need to retrieve all categories? This is because we want to have a drop-down list box to list all announcement names when releasing an announcement, so that users can select the category of the announcement to be published. SelectList is the type used in ASP. net mvc to bind to the drop-down list. It has many reload constructor methods. I use three parameters, which indicate the enumeration of generated data, the field name bound to the value, and the field name bound to the list name. In this example, all object sets of classification are bound to the drop-down list, and the ID attribute is used as the value and the Name attribute is used as the Name displayed in the list box.

If we do not need a drop-down list box to display all categories, the Release method only needs one line of return View ("Release.

After the Action method is complete, we still need the view. Create the Announce directory under the Views directory, and then create the Release. aspx view under the Announce directory. The Code is as follows.

Release. aspx:

<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "Release. aspx. cs "Inherits =" MVCDemo. views. announce. release "%> <% @ Import Namespace =" MVCDemo. models. entities "%> <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <Title> 

The code is not complex, but pay attention to a few points. Not much about categories. This is a list of all categories we passed in just now. I think what you may be confused about is the Html. * ** in fact, Html is an object in ViewPage, and ViewPage is the base class of all views.) The main difference between Html and ViewPage is to generate various form items, in fact, it has other functions), such as Html. beginForm indicates that a form tag is started here, while Html. of course, the EndForm is the end of the form tag. Others. I believe you can guess the name.

As for why we do this, we do not directly use the original HTML tag. I will not talk about it more, but we will naturally understand it later. At present, as long as you know, this can avoid a url problem and make the url more flexible.

Return to this page, BeginForm has three parameters: the Action name of the request to be submitted, the Controller name of the request to be submitted, and the request method. Therefore, this page means to use the post method to request the http: // localhost/Announce/DoRelease Action to process our request.

The page contains three input forms and a submit button. The three input forms are the Title text box, the Content text field, and the Category drop-down list box. Note how the drop-down list is bound, as long as the SelectList containing data is used as the second parameter. The page is as follows:

Process requests

Now we can enter the information, but if you click submit after the input, you will find a classic 404 error. As we have just said, the Action submitted to the form is DoRelease under Announce, but this Action is not available now, of course, it will be 404. Next, we will establish this processing program.

Return to AnnounceController and create the Action method DoRelease. The Code is as follows.

AnnounceController. cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MVCDemo.Models;
using MVCDemo.Models.Interfaces;
using MVCDemo.Models.Entities;
namespace MVCDemo.Controllers
{
public class AnnounceController : Controller
{
public ActionResult Release()
{
ICategoryService cServ = ServiceBuilder.BuildCategoryService();
List categories = cServ.GetAll();
ViewData["Categories"] = new SelectList(categories, "ID", "Name");
return View("Release");
}
public ActionResult DoRelease()
{
AnnounceInfo announce = new AnnounceInfo()
{
ID = 1,
Title = Request.Form["Title"],
Category = Int32.Parse(Request.Form["Category"]),
Content = Request.Form["Content"],
};
IAnnounceService aServ = ServiceBuilder.BuildAnnounceService();
aServ.Release(announce);
ViewData["Announce"] = announce;
return View("ReleaseSucceed");
}
}
}

We can see that it first creates an AnnounceInfo object class to store the information of this new announcement. Note how it gets the form information. By the way, the Request is used. form ["Form name"], which is a way to obtain Form information. Of course, there are other methods, but I recommend this method. Note that the form name here is the name when the form is generated using the Html. *** method.

OK. The following describes how to call the business logic component to release the announcement function.

But there is a problem here. Our business logic component is Mock, that is to say, we did nothing. If it is a real business logic component, we can go to the database to see if the announcement information has been successfully added, but there is no such information. How can we prove that the form data has been passed over? So I tried to add a new ReleaseSucceed view to display the information of the new announcement. This proves that we have actually passed the form information. The ReleaseSucceed view is as follows:

ReleaseSucceed. aspx:

<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "ReleaseSucceed. aspx. cs "Inherits =" MVCDemo. views. announce. releaseSucceed "%> <% @ Import Namespace =" MVCDemo. models. entities "%> <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

This Code does not need to be explained too much. Below, we enter some information and submit it for a look:

No, I did not lie to you. The form data is actually passed!

Summary

Through these four articles, we have learned the basic principles of ASP. net mvc, and will present data pages and pass form data processing. With this, the vast majority of major development projects can be handled. Starting from the next article, we have some advanced content. Next I will talk about how ASP. net mvc works with ASP. net ajax and JQuery. Later I will talk about the interceptor and the combination of Silverlight.

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.