ASP. NET MVC Learning---(v) MVC first Experience

Source: Internet
Author: User

After the pre-n-much cushion

We've probably got to know the guy with the name M VC.

So today we're going to experience a

How to experience it?

Let's do a little example ~

Examples of MVC additions and deletions


Database or before our old friend

Diagram:

The data in the table is filled in.

T_users

Just use it, haha.

The T_users table is now required for additional pruning

Open the Car ~


Go back to the previously created MVC project

Create a new empty controller named home under the Controllers folder


What is returned when the browser requests the index method under home?

It's the homepage, of course.

Here our main page is the display t_users data list

The code is as follows:

First we need an EF context instance, which is a must for        private entities dbentities = new entities ();        T_users data is queried through the data context and the public        ActionResult Index ()        {            ///The data for the T_users table is taken out            var users = DbEntities.T_Users.Where (U = True). ToList ();            and handed over to Viewdata.model            Viewdata.model = users;            return View ();        }
What kind of plane is this viewdata.model?

Don't worry ~

Let's go down first.

Right-click Add View on Index

Be careful not to use the master page first Oh ~

The index.cshtml code is as follows:

@{    Layout = null;} <! DOCTYPE html>

A very formal HTML page

Wait a minute

What's the layout=null of the head?

Layout is the meaning of a placement

We can see that layout=null was wrapped in a @{}.

We said earlier.

This is a syntax for the Razor view engine, so long it's obvious that this is a line of C # code

In fact, it is the role of this page layout page (also can be said to be a master page) empty

Because we don't have a choice when we create a new view.

If you choose to use a master page, layout points to a master page file


So let's go down

In this HTML page

Use a table tag to display t_users data

<table id= "Tblist" >            <tr>                <td>id                </td>                <td>username                </td >                <td colspan= "2" > Operations                </td>            </tr>            @foreach (Var u in Model)            {                <tr >                    <td>@u.id                    </td>                    <td>@u.username                    </td>                    <td>                        <a href= "/home/modify/@u.id" >Modify</a>                    </td>                    <td>                        <a href= "/home/ Delete/@u.id ">Delete</a>                    </td>                </tr>            }        </table>

This piece of code is not difficult.

But where does the model for the Foreach loop come from, and why does it have the data we need?

Think back.

Have we given the users to a model property of ViewData before?

Yes, the model property of ViewData can be accessed directly from the model in the foreground

In the background, you can even do this:

Public ActionResult Index ()        {            //t_users The data of the table is taken out            var users = dbEntities.T_Users.Where (U = True). ToList ();            and handed over to Viewdata.model            //viewdata.model = users;            Return view (users);//Direct users as parameters to the view, you can use the Model property directly in the foreground to get the data        }
The effect is the same in both ways

Don't believe you try ~ I will lie to you?

Try again without money ~


Then there may be a problem

What if I want to send two data to the front desk?

Are you using model?

So it's not covered?

That's when ViewBag is coming.

We're changing the code to look like this.

T_users data is queried through the data context public        ActionResult Index ()        {            ///t_users table data is taken out            var users = Dbentities.t_ Users.where (U = True). ToList ();            and handed over to Viewdata.model            //viewdata.model = users;            Pass data to foreground            viewbag.users = Users through ViewBag;            return View ();        }

Attention!

The users property behind ViewBag is not a fixed

Other words

You can according to your hobbies, whatever you name ViewBag properties, and then just give the data to it ok!

Is that cool? ~

Of course, the Model property is not available at the front desk now.

@foreach (Var u in viewbag.users)            {                <tr>                    <td>@u.id                    </td>                    <td>@u. UserName                    </td>                    <td>                        <a href= "/home/modify/@u.id" >Modify</a>                    </td>                    <td>                        <a href= "/home/delete/@u.id" >Delete</a>                    </td>                </tr>            }
In the background, you use ViewBag to assign the value of the data, in the foreground also through this property to fetch data
So we can pass N-more data at random through ViewBag.

Very convenient ~

Now let's look at the way the site works (right-click on the MVC project to view it in the browser)

The data is out.

But..

That's ugly, isn't it?

Add Style ~


Save, refresh

Is it nice to have a little bit = =

Just use it ~


Okay, the query is done.

Then let's do the new

<tr>            <td>id            </td>            <td>username            </td>            <td> operation            </ td>            <td>                <a href= "/home/create" > New </a>            </td>        </tr>

Forgive me for finding a place to plug in a hyperlink ....

A corresponding create method should be added to the home controller in the background

Returns the new page public        ActionResult Create ()        {            return View ();        }

or right-click to add a view

Show a new page

<body>    <form action= "/home/create" method= "POST" >        <input type= "text" name= "txtUserName"/ >        <input type= "Submit" value= "Add"/>    </form></body>

See this form action point to home create method There are students will have questions

The new page shown earlier also points to the Create method, and now the submit data form also points to the Create method

What the hell?

On the code:

Use HttpPost to mark this method only when the POST request is executed        [httppost] public        actionresult Create (t_users user)        {            string UserName = request.form["txtUserName"];            user = new T_users () {UserName = UserName};            DBENTITIES.T_USERS.ADD (user);            Dbentities.savechanges ();            Redirect to the Index method, which acts as the Response.Redirect            return Redirect ("/home/index") of WebForm;        }


Now you get it.

We just need to add a [HttpPost] tag before the method to OK

Conversely [httpget] of course, only get requests will be executed.

Good

The code finishes, rebuilds, and then refreshes the page

Click the new hyperlink, the new page appears

Isn't it a little simple ...

Whatever.

Click the Add button to submit the form

Successfully added ~


Next in the background add a modify Modify method

Show Modify page public        actionresult Modify (int id)        {            ////////////////by ID) the corresponding data in database            var user = DbEntities.T_Users.Where ( U = u.id = = Id). FirstOrDefault ();            return View (user);        
Add view, HTML code:

<body>    <form action= "/home/modify/@Model. Id" method= "POST" >        <input type= "text" Name= " UserName "Value=" @Model. UserName "/>        <input type=" Submit "value=" Save Changes "/>    </form></body >
One thing to note here is that the value of the Name property of the text box label is best for the property name of the corresponding entity

What do you mean?

For the example above,

T_users has a UserName attribute, the text box is set for this property, so Name= "UserName"

If there is a text box for the id attribute, then the name of the text box is preferably equal to the ID

Why do you do this?

Because if you name= specific entity attributes,

When the form is submitted to the background, the Modify method is received with a t_users parameter, and the label value of the name value and the T_users property of the form is automatically populated in the corresponding property of the T_users object.

Such as:

Modify method for receiving a POST request        [HttpPost] public        actionresult Modify (t_users user)//if the label in the form has the name value equal to the user's property name The system automatically populates the values in the form into this user entity        {            //Append entities to the data context, and sets the modification state of the            property var entry = dbentities.entry (user);            Entry. state = entitystate.unchanged;            Entry. Property ("UserName"). IsModified = true;            Dbentities.savechanges ();            Return Redirect ("/home/index");        }

This is called model binding.

Of course, you might as well not follow this rule.

Just need to receive the parameter of the form separately ~

At this point we regenerate and refresh the page

Click Modify Hyperlink

At this point, an error may occur, such as:

Don't worry, don't panic when you see the anomaly.

This is a set of MVC entity validation

We add a constructor for the home controller class and turn off entity validation in the constructor

Public HomeController ()        {            //off entity validation            dbEntities.Configuration.ValidateOnSaveEnabled = false;        }

Now in to regenerate and refresh ~

Click Save


Successfully modified ~


The final deletion method is simple.

Delete method public        actionresult Delete (int id)        {            t_users user = new T_users () {id = id};            DbEntities.T_Users.Attach (user);            DbEntities.T_Users.Remove (user);            Dbentities.savechanges ();            Return Redirect ("/home/index");        }

Click here to delete the hyperlink to execute the Delete method

If necessary, you can also add a view to show the data to delete, and then click OK to delete ~


Finally, a little question about generating a drop-down box

If you want the t_products entity associated with the user entity to be displayed with a drop-down box when you display the Modify page

The T_products table is as follows:

The first approach:

Retrieve the corresponding t_products data in the background

Show Modify page public        actionresult Modify (int id)        {            ////////////////by ID) the corresponding data in database            var user = DbEntities.T_Users.Where ( U = u.id = = Id). FirstOrDefault ();            Query the data that belongs to the object in the T_products table            var products = DbEntities.T_Products.Where (p = = P.uid = = ID). ToList ();            and pass it into ViewBag            viewbag.products = Products;            return View (user);        

Front Desk Show:

<body>    <form action= "/home/modify/@Model. Id" method= "POST" >        <input type= "text" Name= " UserName "Value=" @Model. UserName "/>        <select name=" t_products ">            @foreach (var p in viewbag.products)            {                <option value= "@p.id" >@p.ProName</option>            }        </select>        <input type= " Submit "value=" Save Changes "/>    </form></body>

Page effect:

This is the normal use of the HtmlSelect label method

But there's another way to provide Lee in MVC.


The second approach:

First look at the foreground code

<body>    <form action= "/home/modify/@Model. Id" method= "POST" >        <input type= "text" Name= " UserName "Value=" @Model. UserName "/>        @* First Practice:        <select name=" t_products ">            @foreach (Var p in viewbag.products)            {                <option value= "@p.id" >@p.ProName</option>            }        </select>*@                @* The second approach, use the HtmlHelper class *@        @Html. DropDownList ("T_products", viewbag.products as ienumerable< selectlistitem>)        <input type= "Submit" value= "Save Changes"/>    </form></body>

HtmlHelper class when MVC built a class that helps programmers quickly generate HTML code, can be abbreviated to HTML

For example, the html.dropdownlist in this example ultimately generates a drop-down box

The first parameter is the Name property of the drop-down box, and the second parameter is a collection of ienumerable<selectlistitem> types (that is, the data to be displayed, but first to Ienumerable<selectlistitem >.)

So in the background

We get the data we want to show first.

Show Modify page public        actionresult Modify (int id)        {            ////////////////by ID) the corresponding data in database            var user = DbEntities.T_Users.Where ( U = u.id = = Id). FirstOrDefault ();            The first approach            //queries the data that belongs to the object in the T_products table            //var products = dbEntities.T_Products.Where (p = = P.uid = = ID). ToList ();            and pass it into ViewBag            //viewbag.products = Products;            The second approach            list<selectlistitem> products =                DbEntities.T_Products.Where (p = = P.uid = = ID)                    . ToList ()//Query out T_products collection                    . Select (p = = new SelectListItem {Text = p.proname, Value = P.id.tostring ()})//Convert entity collection to SelectListItem type                    . ToList ()//In conversion to list<selectlistitem> collection            //incoming VIEWBAG            viewbag.products = Products;            return View (user);        

Regenerate and Refresh

The effect is the same in both ways

The second is that MVC has something special.

It may be very unaccustomed to use now.

But HtmlHelper is a class often used by MVC developers.

We will explain in detail later


OK, now a set of MVC basic additions and deletions have been completed

It's a little bit rewarding, isn't it?


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.