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")]
        [DataType(DataType.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;

            GenreLst.AddRange(GenreQry.Distinct());
            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:

<!--Query-->
    @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" />
    </div>
    }

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">
               //......
            </div>
        </div>

More HTML:

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

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

1,255 thoughts on “MVC:ASP.NET MVC 5 in touch”

  1. First of all I want to say great blog! I had a quick question which
    I’d like to ask if you do not mind. I was curious to find
    out how you center yourself and clear your thoughts prior to writing.
    I’ve had a hard time clearing my mind in getting my ideas out there.
    I do take pleasure in writing however it just seems like the
    first 10 to 15 minutes are wasted simply just trying to figure out how to begin.
    Any suggestions or hints? Appreciate it!

  2. We’re a bunch of volunteers and opening a brand new scheme
    in our community. Your site provided us with valuable information to work on. You’ve performed a formidable
    activity and our entire neighborhood shall be thankful to you.

  3. Levothyroxine Tablets To Buy Cialis Immagini Secure Tab Doryx In Internet Shipped Ups Free Doctor Consultation cialis Order Generic Propecia 1mg Pastilla Cialis Alcohol Finasteride Farmaco Propecia

  4. If you would like to increase your familiarity only keep visiting this web page and be updated with the latest gossip posted here.

  5. jasa website medan, jasa website sekolah, web sekolah gratis, jasa web stabat, jasa website asahan, jasa website batubara, web sekolah murah, jasa toko online, jasa web murah terbaik, jasa web murah

  6. I absolutely love your blog and find a lot of your post’s to be exactly I’m looking for.
    Do you offer guest writers to write content
    for you personally? I wouldn’t mind writing a post or elaborating on a few of the subjects you write related to
    here. Again, awesome weblog!

  7. I do consider all of the ideeas you have offered to your
    post. They’re verry convincing andd can definitely work. Nonetheless, the posts are very brief for
    newbies. Could you please lengthen them a bit from subsequent time?

    Thanks for tthe post.

  8. hello there and thank you for your inforation – I have certainly pickked up something new from right
    here. I did however expertise several technical issues using
    this site, as I explerienced to reload the web sote lots of times previous to I could get it
    to load correctly. I had been wondering iff your
    hosting is OK? Not that I am complaining, but slow loading instances times will often affect your
    placement in google and can damage your high-quality score if advertising aand marketing with Adwords.
    Well I’m adding this RSS to my email andd can lookk out for much more of your respective fascinating content.

    Ensure that you update this again very soon.

  9. An outstanding share! I’ve just forwarded this onto a colleague who haad een conducfting a little
    research on this. Annd he actually bought me breazkfast because I stumbled
    upon it for him… lol. So allow me to reword this….
    Thank YOU for the meal!! But yeah, thanks for spending some time
    to discuss this issue here on your web page.

  10. Thanks for your post. I also believe laptop computers are getting to be more and more popular right now, and now are often the only form of computer utilized in a household. This is due to the fact that at the same time that they are becoming more and more affordable, their working power keeps growing to the point where they are as robust as personal computers out of just a few years ago.

  11. Thanks for the tips you have shared here. Something important I would like to convey is that laptop or computer memory needs generally rise along with other advances in the technologies. For instance, any time new generations of processor chips are brought to the market, there’s usually a similar increase in the size and style calls for of both laptop or computer memory and hard drive space. This is because the software program operated by way of these processors will inevitably increase in power to leverage the new know-how.

Leave a Reply

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