In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is about how MVC3 can quickly build Web applications. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Unlike winform applications, Web applications can provide users with a smoother and more comfortable experience by simulating the window operation of winform, so that users can be as comfortable as desktops in browsers. In the interface framework we are most familiar with jquery ui, there are Ext and so on, after a series of screening, we finally decided to use easyui, documentation tutorial examples are more comprehensive js ui framework. First of all, let's take a look at the js file used.
Jquery master file easyui master file verification component form component easyui Chinese culture verification component
We add it to mvc's Shared/_Layout.cshtml. In this way, all Layout=null views of our project have easyui support.
In MVC3, when you right-click to add a controller, the wizard gives you a choice:
In the template, we choose to use the entity framework and generate the relevant actions and views,Model to select the corresponding table name (class name) in your entity framework, and DataContext to select the context class
The Views engine chooses Razor, and the two check boxes in the advanced options are removed, because we do not need to refer to the built-in script library, nor do we need to select layout (do not choose layout,MVC default that view uses Shared/_Layout.cshtml, that is, the file where we just added the js file link).
Make sure that the T4 template you downloaded in the previous article is put in its place (it is best to back up the original). When you click Add, vs will automatically add the corresponding controller under Controllers and add Create, Edit, Delete, Details and Index files under the views folder. Let's look at their contents one by one:
In the controller, action has automatically added it for you.
Private BsmisEntities db = new BsmisEntities (); / GET: / User/ public ViewResult Index () {return View ();} / GET: / User/Create public ActionResult Create () {return View () } / POST: / User/Create [HttpPost] public ActionResult Create (T_User t_user) {JsonResult result = new JsonResult (); result.Data = true Try {if (t_user.Enable = = null) t_user.Enable = 0; db.T_User.AddObject (t_user); db.SaveChanges () } catch (Exception ee) {result.Data = ee.Message;} return result } / GET: / User/Edit/5 [OutputCache (Location = OutputCacheLocation.None)] public ActionResult Edit (int id) {T_User t_user = db.T_User.Single (t = > t.UserID = = id); ViewBag.DepartmentID = new SelectList (db.T_DepartmentInfo, "DepartmentID", "Code", t_user.DepartmentID) Return View (t_user);} / POST: / User/Edit/5 [HttpPost] [OutputCache (Location = OutputCacheLocation.None)] public ActionResult Edit (T_User t_user) {JsonResult result = new JsonResult (); result.Data = true Try {db.T_User.Attach (t_user); db.ObjectStateManager.ChangeObjectState (t_user, EntityState.Modified); db.SaveChanges ();} catch (Exception ee) {result.Data = ee.Message } return result;} / POST: / User/Delete/5 [HttpPost, ActionName ("Delete")] public ActionResult DeleteConfirmed (int id) {JsonResult json=new JsonResult (); json.Data=true; try {T_User t_user = db.T_User.Single (t = > t.UserID = = id) Db.T_User.DeleteObject (t_user); db.SaveChanges ();} catch (Exception ee) {json.Data=ee.Message;} return json } / data display, paging information / public JsonResult List (int page Int rows) {var Q = from u in db.T_User join d in db.T_DepartmentInfo on u.DepartmentID equals d.DepartmentID orderby u.UserID select new {UserID = u.UserID UserName = u.UserName, Address = u.Address, Birth = u.Birth, DepartmentID = u.DepartmentID, DepartmentName = d.Name, Enable = u.Enable Gendar = u.Gendar, IDCardNumber = u.IDCardNumber, LastAccessIP = u.LastAccessIP, LastAccessTime = u.LastAccessTime, LogonTimes = u.LogonTimes, Password = u.Password PostCode = u.PostCode, RealName = u.RealName, Tel = u.Tel, Province = u.Province, City = u.City Area = u.Area} Var result = q.Skip ((page-1) * rows) .Take (rows). ToList (); Dictionary json = new Dictionary (); json.Add ("total", q.ToList () .Count); json.Add ("rows", result); return Json (json, JsonRequestBehavior.AllowGet);}
These action correspond to create, delete, edit, and index views (detail we don't normally need, so I don't have the corresponding generated code in my template) you can compare it with the code generated by the native template. Later, we will add some action to the controller, such as checking whether the name is the same name or not.
[OutputCache (Location = OutputCacheLocation.None)] public JsonResult CheckRealNameExist (string RealName, int UserID) {JsonResult result = new JsonResult (); result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; result.Data = false Try {if (UserID = = 0) {if (db.T_User.Any (p = > p.RealName = = RealName)) {return result }} else {if (db.T_User.Any (p = > ((p.UserID! = UserID) & & (p.RealName = = RealName) {return result } catch (Exception) {return result;} result.Data = true; return result;}
The return value is usually jsonresult. In this way, when you visit http://localhost:1233/User/CheckRealNameExist?RealName= Zhang San & UserID=0 in your browser, you will get a true or false value. Is it a bit like webservice?
Similarly, generated in the Views folder Create, Edit, Details, Delete, Index five files, of which Details and Delete we do not need, because we want to use a more friendly asynchronous deletion (after the user clicks delete, the page does not refresh, after success, the browser slides below the prompt, 3 seconds after closing, failure slips out the failure message, does not automatically close / use the messager component in easyui). The following is the js in Index:
/ / delete function del () {var id = getselectedRow (); if (id! = undefined) {$.messager.delete ('confirm', 'confirm?', function (r) {if (r) {var url = 'User/Delete/' + id) $.post (url, function () {}) .success (function () {$.messager.show ({title: 'prompt', msg: 'deleted successfully' Timeout: 3000, showType: 'slide'}) $('# dg'). Datagrid ('reload');}) .error (function () {$.messager.alert (' error', 'deletion error');}) });}}
After we delete Details and Delete, there are only three files: Index, Create and Edit. The relationship between these three files is that Index contains add and edit buttons, and then click and use js to load the corresponding actionresult into div to achieve the effect of new pop-up window and editing.
/ / create a new function c_dlg () {var url = 'User/Create'; $(' # croudlg') .show () Load (url, function () {$(this) .load ({title: 'add', buttons: [{text: 'submit', iconCls: 'icon-ok'' Handler: function () {$('# canalform') .submit () }}, {text: 'cancel', handler: function () {$('# croudlg`) .dialog ('close') }}]});});} / / Edit box function e_dlg () {var id = getselectedRow (); if (id! = undefined) {var url = 'User/Edit/' + id $('# estrangdlg`). Show () Load (url, function () {$(this) .load ({title: 'edit', buttons: [{text: 'submit') IconCls: 'icon-ok', handler: function () {$(' # estrangform') .submit () }}, {text: 'cancel', handler: function () {$('# estrangdlg`) .dialog ('close') }}]});})
The c_dlg and e_dlg here are the two Div nodes of the index page:
The above code completes the dynamic loading of the page content returned by the action in the controller into the div and displays in the current (Index) page with the special effects of the pop-up window. The effect is as shown in the figure:
Let's look at the contents of the Create\ Edit view, starting with js
Combotree ({url:'@ Url.Action ("GetComboTreeJson", "Department")'}); $('# cached City`) .combobox (); $('# cached Area`) .combobox () Combobox ({url:'CityDic/List/ID/0', onSelect: function (record) {$('# clocked City`). Combobox ('reload',' CityDic/List/ID/' + record.ID) .combobox ('clear'); $(' # caged Area'). Combobox ('clear') }}); combobox ({onSelect: function (record) {$('# crested Area'). Combobox ('reload',' CityDic/List/ID/' + record.ID) .combobox ('clear');}}) $('# caged Birth`). Datebox (). Datebox ('setValue',' @ now') $("# c_form") .validate ({rules: {UserName: {required: true, remote: {url: 'User/CheckNameExist' Type: "get", dataType: "json", data: {Name: function () {return $('# centering UserName'). Val () }, UserID: function () {return 0 }, RealName: {required:true, remote: {url: 'User/CheckRealNameExist', type: "get" DataType: "json", data: {RealName: function () {return $('# cached RealName') .val () }, UserID: function () {return 0 }, messages: {UserName: {remote: 'duplicate name'} RealName: {remote: 'duplicate name'}}, submitHandler: function (form) {ajaxAdd () }))
This part of js initializes the controls on this page to the corresponding drop-down box or date marquee and so on. The Html is
@ using (Html.BeginForm ("Create", "User", FormMethod.Post, new {id = "c_form"}) {@ Html.LabelFor (model = > model.UserName) "user name:") * @ Html.LabelFor (model = > model.DepartmentID "Organization:") * @ Html.LabelFor (model = > model.Password "password:") @ Html.PasswordFor (model = > model.Password, new {@ class = "{required:true Minlength:5} "}) * confirm password * @ Html.LabelFor (model = > model.RealName "Real name:") @ Html.TextBoxFor (model = > model.RealName, new {@ id= "c_RealName") @ class = "{required:true}"}) * @ Html.LabelFor (model = > model.Gendar, "gender:") @ Html.RadioButtonFor (model = > model.Gendar, "male" New {@ id = "radio1", @ name = "Gendar", @ checked = "checked"}) male @ Html.RadioButtonFor (model = > model.Gendar, "female", new {@ id = "radio2" @ name = "Gendar"}) female @ Html.LabelFor (model = > model.Birth) "date of birth:") @ Html.LabelFor (model = > model.IDCardNumber "ID number:") @ Html.EditorFor (model = > model.IDCardNumber) @ Html.LabelFor (model = > model.Province) "Province:") @ Html.LabelFor (model = > model.City "City:") @ Html.LabelFor (model = > model.Area "District / county:") @ Html.LabelFor (model = > model.PostCode "ZIP code:") @ Html.EditorFor (model = > model.PostCode) @ Html.LabelFor (model = > model.Address) "address:") @ Html.EditorFor (model = > model.Address) @ Html.LabelFor (model = > model.Tel "phone:") @ Html.EditorFor (model = > model.Tel) @ Html.LabelFor (model = > model.Enable "enable:") @ Html.CheckBoxForBool (model= > model.Enable,true,true)}
The same is true in the edit view. When the save button is clicked, execute
$('# canalform') .submit ()
Here our client-side verification is here:
$("# c_form") .validate ({rules: {UserName: {required: true, remote: {url: 'User/CheckNameExist', type: "get" DataType: "json", data: {Name: function () {return $('# clocked Username') .val () }, UserID: function () {return 0 }, RealName: {required:true, remote: {url: 'User/CheckRealNameExist', type: "get" DataType: "json", data: {RealName: function () {return $('# cached RealName') .val () }, UserID: function () {return 0 }, messages: {UserName: {remote: 'duplicate name'} RealName: {remote: 'duplicate name'}}, submitHandler: function (form) {ajaxAdd () })
The submitHandler method provides what to do before verification: ajaxAdd ()
/ / Asynchronous new submission function ajaxAdd () {$('# cformulform') .ajaxSubmit ({url: 'User/Create', beforeSubmit: function () {if ($(' # cSecretform') .form ('validate')! = true) {return false) } if ($("# c_form") .valid ()! = true) {return false;} return true }, success: function (data) {if (data = = true) {$('# dg''). Dialog ('close'); $(' # dg'). Datagrid ('reload') $.messager.show ({title: 'prompt', msg: 'saved successfully', timeout: 2000, showType: 'slide'}) } else {$.messager.show ({title: 'prompt', msg: 'save failed:' + data, timeout: 2000 ShowType: 'slide'}) }); return false;}
Get the data after the asynchronous submission is successful. If the true is successful, close the dialog box, refresh the form, and pop up the prompt. If you fail, the data pops up (usually the reason for the failure, which is returned by the action in controller). Here is the table in Index:
Department user name real name gender The number of birthday phone calls and the last visit to IP Last visit time status @ if (userid! = 0 & & AuthMgr.HasAuth (userid) "add", 5)) {Edit}
Where @ if is used to determine permissions, if the current login user has add permissions, then the "add" button is displayed.
Thank you for reading! This is the end of the article on "how to quickly build Web applications in MVC3". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.