MVC:ASP.NET MVC 5 in touch

Come from an old post named MVC:接触ASP.NET MVC 5  , 2016-07-31

Today is my birthday, but I decide to learn the .NET Framework in continuation (●’◡’●).

Studying in HTML and CSS for some days, I still feel unfamiliar with them though they are both easy, because of some much time in using XAML, I can’t even remember the tags of HTML, so sad… With the hard feeling in C++, I decide to learn the MVC framework in .NET with the less understanding of HTML, after all , I will learn it sooner or later.

I ever have experiences in Web Forms although it’s only a school course in fake level. In brief, the monolithic feelings is alright, the pattern of event-driven-programming is easy to understand, and the code in server is just familiar with the desktop applications in Windows. And it’s the first time for me to use database instead of some xml files, there are still something to learn.

Anyway, I know there is another framework named MVC in ASP.NET, and I even build a project to glance over. My first feelin is that the MVC seems more difficult than Web Forms because it’s more familiar like the MVVM which I ever used in UWP and WPF platform for Windows Desktop. The main point of this framework is how to decouple your code between the units in application. I finally decide to use Web-Forms to do my course-design with anyway. But now, I realize that it still necessary to learn the important framework because the opinion of decoupling is so distinguished and meaningful.

As a beginner, I do have no deep comprehension or illumination in programing, but if you have the same interests like me , there is no harm in groping and coming with me.

1st: About Controller

I don’t think it’s necessary to mention the steps in building project, it’s so boring. So let’s check some specific attributes in the controller of MVC framework.

It’s the default-built controller if you choose the default pattern to begin:

namespace MVCTest001 . Controllers {
    public class HomeController : Controller {
        public ActionResult Index ( ) {
            return View ( );

        public ActionResult About ( ) {
            ViewBag . Message = "Your application description page.";
            return View ( );

        public ActionResult Contact ( ) {
            ViewBag . Message = "Your contact page.";
            return View ( );

The framework use controller to send data and receive response with pages, receive and pass the instructions with Logic part. Though it seems like the ViewModel in MVVM, but they are different. Controller is just like a telephone-operator, or a messenger, with the only duty to send and receive instructions between View and Model in abstract concepts. There is no traditional concept of the View in MVVM, and ViewModel is special and playing a more decisive role. Microsoft suggests that we should keep separation of concerns between the business logic and View. The controller is important.

How to define the controller? Look at this ( RouteConfig.cs in App_Start , and don’t forget to register in Global.ascx ) :

namespace MVCTest001 {
    public class RouteConfig {
        public static void RegisterRoutes ( RouteCollection routes ) {
            /// Block the request
            routes . IgnoreRoute ( "{resource}.axd/{*pathInfo}" );
            routes . MapRoute (
                name: "Default" ,
                url: "{controller}/{action}/{id}" ,
                defaults: new { controller = "Home" , action = "Index" , id = UrlParameter . Optional }

“Home” will be interpreted as “HomeController”, and the “action” will map to a concrete method in this controller, and the last one is the parameter, optionally. The Routing System of MVC is specific and powerful so that we don need to access a concrete code file for View, just in the convention like “{controller/action?parameter=xxx}”, succinct and efficient. And the HtmlHelper in MVC is even more intrepid doughty valiant and stronger extremely, just see the feature of creating a tag like this “<a href=”xxxx”>XXXX</a>” :

<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>

We call this syntax as “Razor”, means it’s sharp like a razor. You will be allowed to use holy sections of C# code in the View part and connect with javascript with the Razor, then you will realize the power and strength of it

There are also many points of controller, but won’t be mentioned here.

2nd: Entity Framework and Code-First Migrations

The existence of Entity Framework in ASP.NET allows us only use code instead of SQL sentences to build and maintain the database.

We can firstly built our entity class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace MVCTest001.Models {
    public class PersonalModel {
        public int ID { get; set; }
        public string Title { get; set; }

        [Display(Name = "Release Date")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",ApplyFormatInEditMode = true)]
        public DateTime ReleaseDate { get; set; }

        public string Genre { get; set; }
        public decimal Price { get; set; }

    public class DBContext:DbContext {
        public DBContext():base("MyDatabase") { }
        public DbSet<PersonalModel> Personals { get; set; }

You can use “base:(“XXXXXXX”)” to save database as a special name. The database engine is LocalDb (a express version of SQL Server, great in using) and you can open the code first migration to update the schema of database when any changes occurred.

3rd: Valiance in code functional integration

It makes me really amazing when I create the controller in the default module: the VS help me to build the whole 4 pages contained with features of Add, Delete, Update and Change. That’s Incredible……( ▼-▼ )

4th: Query functional implementions

The code is succinct:

public ActionResult Index(string movieGenre,string searchString) {
            var GenreLst = new List<string>();

            var GenreQry = from d in db.Personal
                           orderby d.Genre
                           select d.Genre;

            ViewBag.movieGenre=new SelectList(GenreLst);

            var movies = from m in db.Personal
                         select m;

            if(!string.IsNullOrEmpty(searchString)) {
                movies=movies.Where(s => s.Title.Contains(searchString));

            if(!string.IsNullOrEmpty(movieGenre)) {
                movies=movies.Where(x => x.Genre==movieGenre);

            return View(movies);

Then finish the form in HTML like this:

    @using(Html.BeginForm("Index","PersonalModels",FormMethod.Get)) {
    <div class="col-md-10">
        Genre: @Html.DropDownList("movieGenre",(SelectList)ViewBag.movieGenre,htmlAttributes: new { @class = "form-control" })
        Title: @Html.TextBox("searchString",null,"001",htmlAttributes:new { @class = "form-control" })
        <br />
         <br />
        <input type="submit" value="Filter" class="btn btn-default" />

5)About the code style in cshtml

You can use almost pure Html style or Razor to organize your code, any way you like. Maybe the more Html will express better, but the Helper is more easy to use.

More C#:

 <div class="form-group">
            @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">

More HTML:

<div class="form-group">
            <label class="control-label  col-md-2" >@Html.DisplayNameFor(i=>i.ReleaseDate)</label>
            <div class="col-md-10">

Well, it’s only a quick look of the MVC framework, more details will come later, but not today(/▽\=)……

3,239 thoughts on “MVC:ASP.NET MVC 5 in touch”

  1. I think this is anong the most significant information for me.
    And i’m glad reding your article. But want to remark on few general things,
    The site style iss wonderful, the articles is really
    nice : D. Good job, cheers

  2. Paragraph writing is also a excitement, if yoou be
    familiar with then you can write if not it is complicated
    to write.

  3. One thing I’d like to say is that before getting more laptop or computer memory, have a look at the machine within which it is installed. In case the machine will be running Windows XP, for instance, the actual memory threshold is 3.25GB. Installing over this would simply constitute some sort of waste. Make certain that one’s motherboard can handle the actual upgrade quantity, as well. Thanks for your blog post.

  4. I have learned some new things via your weblog. One other thing I’d really like to say is newer personal computer operating systems are likely to allow more memory to get used, but they furthermore demand more storage simply to run. If people’s computer could not handle much more memory plus the newest application requires that storage increase, it might be the time to buy a new Personal computer. Thanks

  5. Interesting blog post. The things i would like to contribute is that computer system memory is required to be purchased but if your computer is unable to cope with everything you do by using it. One can deploy two good old ram boards containing 1GB each, for instance, but not one of 1GB and one with 2GB. One should always check the car maker’s documentation for own PC to be certain what type of storage is essential.

  6. Thanks for your post. I also think laptop computers have become more and more popular right now, and now in many cases are the only kind of computer used in a household. This is because at the same time that they’re becoming more and more economical, their processing power is growing to the point where they’re as strong as pc’s coming from just a few years ago.

  7. Some tips i have observed in terms of pc memory is there are specs such as SDRAM, DDR or anything else, that must fit in with the requirements of the motherboard. If the pc’s motherboard is kind of current and there are no main system issues, upgrading the ram literally will take under an hour or so. It’s among the list of easiest laptop upgrade methods one can visualize. Thanks for revealing your ideas.

  8. This is very interesting, You’re an excessively professional blogger. I’ve joined your rss feed and sit up for searching for extra of your excellent post. Also, I have shared your website in my social networks

  9. You really make it seem so easy with your presentation but I
    find this topic to be actually something that
    I think I would never understand. It seems too complicated and very broad for me.
    I am looking forward for your next post, I’ll try to get the hang of it!

  10. Just desire to say your article is as amazing. Thee clearness in your publish is simply
    cool and that i can think you are an expert on this subject.
    Fine together with your permission allow me to rab your feed to keep
    updated with forthcoming post. Thanks a million and please continue the enjoyable

  11. Hello! I jut wanted to ask if you evesr have any problems
    with hackers? My last blog (wordpress) was hacked and I ended up lossing months
    of hard work due to no dasta backup. Do you have any methods to stop hackers?

  12. One thing is that one of the most typical incentives for using your credit card is a cash-back or maybe rebate provision. Generally, you get 1-5% back in various expenditures. Depending on the card, you may get 1% back again on most buying, and 5% in return on buying made going to convenience stores, filling stations, grocery stores as well as ‘member merchants’.

  13. Aw, this was a really nice post. In thought I would like to put in writing like this additionally ?taking time and precise effort to make an excellent article?however what can I say?I procrastinate alot and on no account appear to get something done.

  14. You really make it appear really easy with your presentation but I to find this matter to be really one thing that I feel I would never understand. It sort of feels too complicated and very huge for me. I’m looking forward to your next put up, I’ll attempt to get the hang of it!

Leave a Reply

Your email address will not be published. Required fields are marked *