Easyui+mvc+ef Simple User Management demo (problem and resolution)

Source: Internet
Author: User
Tags add time connectionstrings

Original: http://www.cnblogs.com/xishuai/p/3635192.html

Write in front
    1. Iframe-src

    2. EntityFramework version

    3. ConnectionStrings

    4. View, Action, page jump

    5. Easyui in DataGrid bindings

    6. Add, modify, and delete data

    7. , complete sample Demo download

    8. Postscript

About Easyui know almost, just want to combine MVC, EF to do a simple user management demo, actually not much thing, but this is a side dish I do for the first time. The main is familiar with the process, of course, also encountered some problems, go a lot of detours.

The process of the demo is not described in detail, we can download under the article to see, this is only recorded in the process of doing some of the problems and solutions, hoping to help the same side dishes like me, but also welcome the great God guidance.

Hands-on, clothed.

Iframe-src

Easyui the left menu is linked to the content area of the Tab,tab page is usually an IFRAME, in ASP. We generally use the following src:

1 <iframe scrolling= "Auto" frameborder= "0"  src= "home.html" style= "width:100%;height:100%;" ></iframe>

In MVC, if you use this SRC link directly you will not find the page address, we need to do this:

1 <iframe scrolling= "Auto" frameborder= "0"  src= "Home/getview?viewpara=home" style= "width:100%;height:100%;" ></iframe>

The SRC format is "{Controller}/{action}?viewpara={viewname}" and the controller code:

1///<SUMMARY>2//         iframe get view 3//</summary>4//         <returns></returns>5 Public         ActionResult GetView (String Viewpara) 6         {7             return View (Viewpara); 8         }

If you fill in the viewname is not in this directory, to fill in relative directory such as: src= "home/getview?viewpara=. /user/user_list ".

EntityFramework version

On this issue, here I want to describe in detail, although the final solution is very simple, but it took me a few hours to find out the problem, very depressed.

MVC Our Submission form is generally used AAJX, following the login submission form to check the account number:

1             $.ajax ({2                 URL: "Login/checkuserlogin", 3                 Type: "POST", 4                 dataType: "JSON", 5                 data: {"Name": $ ("#" UserName "). Val ()," Password ": $ (" #Password "). Val ()}, 6                 //contenttype:" Application/json ", 7                 success: function (data) {8                     if (Data.result = = "Success") {9                         window.location.href = "/home/index";                     }11                     else {                         alert (data.content);                         window.location.href = "/login/login/";                     }15                 },16                 Error: function (XHR, error, ex) {                     alert ("There is an error, please try again later, for inconvenience, please understand");                     window.location.href = "/login/login/"; 19                 }20             });

Can see the JS code is not a problem, from the URL is submitted to the login controller checkuserlogin, then our code can write:

 1//<summary> 2///Process Login Information 3//</summary> 4//<param name= "UserInfo "></param> 5//<returns></returns> 6 public jsonresult checkuserlogin (UserInfo user Info) 7 {8//return Json (New {result = "error", content = "User name password error, please check"}); 9 using (Ea  Syuidemodbentities db = new Easyuidemodbentities ()) {One-//linq query for VAR users = from p in db.  UserInfo13 where p.name = = Userinfo.name && P.password = = Userinfo.password && p.enable = = True14 Select P;15 if (users. Count () > 0) userInfo = users. FirstOrDefault (); response.cookies["UserName"]. Value = userinfo.name;19 response.cookies["UserName"]. Expires = DateTime.Now.AddDays (7), return Json (new {result = "success", content = "}")}22 Else23 {24 Return Json (New {result = "error", content = "User name password error, please check"}); 25}26}27}

Easyuidemodbentities is the context in which we create the model, as we can see from the code, we set a breakpoint on line tenth and run it:

The above reported is "Internal Server Error" errors, we above in the Checkuserlogin method set the breakpoint is not executed at all, the Internet to find a lot of information, but no way to find a solution, I originally thought it was the Ajax submission problem, Then it's OK to change the get commit to block out the code in the using, which means there's nothing wrong with Ajax.

Back to the "Internal server Error" this paragraph, literally understand is the host server problem, online said is the background code problem, at that time did not pay attention to, thought no problem ah, finally really can not find other reasons, a new console program, Copy the code from the using in the past, run it, report the following error:

From the results of the above debugging, we are getting closer to the truth, and also stating: Don't trust your own code too much. The EntityFramework version problem can be seen from the exception.

The first one is the entityframework version of the console program, the second is the entityframework version of the instance model, because when we create the console program, the Nugget add package EntityFramework is the latest version added, When creating a new entity model, the 4.4 version is added, and we can change the EntityFramework version to match it.

ConnectionStrings

The above problem is solved, we can debug the code, but the following problems appear:

The exception indicates that the Easyuidemodbentities connection string could not be found. But we created the Entity Model App. config file with the easyuidemodbentities connection string, searched the web, said to be in the main program also to add the connection string, MVC add easyuidemodbentities connection string, run OK.

View, Action, page jump

After solving the SRC related, we now want to do: Login input user name and password, if the correct jump to the main interface, about MVC in the JS jump page we can write:

1       //window.location.href = "Home/getview?viewpara=index"; 2       //window.location.href = "@Url. Content ("/home/ index/")"; 3       window.location.href = "/home/index";

Home indicates that Controller,index represents the action, the main interface of the SRC or according to our resolution above to write, jump to the main interface will appear the following situation:

If we change the route directly to browse the main interface, it is normal to browse, but from the above can be seen in the IFRAME SRC is not implemented to the home controller, the web also did not search the relevant information, finally add the following code in the home controller is good:

1 public         ActionResult Home () 2         {3             return View (); 4         }

I don't know what the situation is. Let's do another experiment: we're going to write the home page of the main interface:

1 <iframe scrolling= "Auto" frameborder= "0"  src= "home/getview?viewpara=. /user/user_add "style=" width:100%;height:100%; " ></iframe>

SRC does not point to home and points to the User_add,home controller code in the user directory:

1 public         ActionResult Index () 2         {3             return View (), 4         } 5 public         ActionResult Home () 6         {7             ret Urn View (); 8} 9///<SUMMARY>10//         iframe get view one         ///</summary>12//         <returns>< /returns>13 public         ActionResult GetView (String Viewpara) (             Viewpara)         

Setting breakpoints in three actions, jumping from the login page to the main interface will find that index and home are executed, but the normal should be index and getview, because we do not write any code about the home link, if we go directly to the main interface, Will find that index and GetView are executed, from above may understand some, but do not seem to understand, this remains to be studied.

In addition to the main interface when loading the home link problem, there is the menu click IFrame Problem, the solution is to write an action on each page.

Easyui in DataGrid bindings

Easyui using the DataGrid binding data when you do it may also be used, mainly in accordance with a certain JSON format output, this is my first time to do, encountered the following problems, spent a lot of time:

1//         <summary> 2//         get all information from users 3//         </summary> 4//         <returns></returns> 5 Public         ActionResult Getalluserinfo () 6         {7             int pageIndex = request["page"] = = null? 1:int. Parse (request["page"]); 8             int pageSize = request["Rows"] = = null? 20:int. Parse (request["Rows"]); 9             using (easyuidemodbentities db = new easyuidemodbentities ()) one by one             {ten                 var data = from U in db. UserInfo13                            Select New {u.id, u.name, U.phone, U.password, U.mail, U.createtime, u.address, u.enable};14                 var re Sult = new {total = data. Count (), rows = Data};15                 return JSON (result, jsonrequestbehavior.allowget),             }17             return JSON ( Datajson);         

Front-End Code:

 1 $ (function () {2//Initialize popup Form 3 inittable (); 4}); 5 6//Initialize table 7 function inittable () {8 $ (' #test '). DataGrid ({9 title: ' User list ')                 , Iconcls: ' Icon-user ', one-loadmsg: ' Data Loading ... ', nowrap:true,13                 autorowheight:true,14 striped:true,15 URL: '/user/getalluserinfo ', 16 Sortname: ' ID ', SortOrder: ' ASC ', border:true,19 REMOTESORT:FA                 lse,20 IDfield: ' ID ', pagesize:10,22 pagination:true,23                     rownumbers:true,24 columns: [[[+] field: ' CK ', checkbox:true},26 {field: ' id ', title: ' ID ', width:50, sortable:true},27 {field: ' Name ', Title: ' Username ', width:1 XX, sortable:true},28 {field: 'Phone ', title: ' Telephone ', width:150, sortable:true},29 {field: ' Password ', title: ' Password ', width:150, Sor                     Table:true},30 {field: ' Mail ', title: "EMail", width:150, Sortable:true},31 {field: ' Createtime ', title: ' Add Time ', width:150, sortable:true,33 form Atter:function (value, row, index) {//return (eval (Value.replace (/\/date\ (\d+) \) \//gi, "n EW Date ($))). Pattern ("yyyy-m-d h:m:s");}36},37 {fi ELD: ' Address ', title: ' Addresses ', width:250, sortable:true},38 {The ' is ' enabled '                                 , field: ' Enable ', width:80, Formatter:function (Val, RowData, index) {41 if (val)}                             Return ' <a class= ' grid_enable "href=" javascript:void (0) "> ' + val + ' </a> '; 42 } else {<a class= "grid_unenable" href= "javascript:void (0)" > ' + val + ' &lt                 ;/a> '; 44}45}46}47]],48 Onloadsuccess:function () {$ (". Grid_enable"). LinkButton ({text: ' Enabled ', Plain:true, ico Ncls: ' Icon-ok '}); $ (". Grid_unenable"). LinkButton ({text: ' Forbidden ', plain:true, iconcls: ' Icon-stop '} ); 51},52}); 53}

Front-end code is not a problem, we use Easyui binding data is also used, but if the above code is not displayed data, and finally found the reason is the var result format problem, modify the code as follows:

1             using (easyuidemodbentities db = new Easyuidemodbentities ()) 2             {3                 var temp = from u in db. UserInfo Select U; 4 Total                 = temp. Count (); 5                 var users = temp. OrderByDescending (s = s.id) 6                      . Skip<userinfo> ((pageIndex-1) * pageSize). Take<userinfo> (pageSize); 7                 list<userinfo> List = new list<userinfo> (); 8                 foreach (UserInfo item in users) 9                 {Ten                     List. ADD (item),                 }12                 var data1 = new13                 {Total                     = total,15                     rows = list16                 };17                 return Json (data1);             

Or, modify rows = users. Tolist<userinfo> (); implicit typing into generics, in fact, is the lack of knowledge of their own, about the implicit type and generics, and the use of the JSON () method, although to find problems and solutions, but the deep reason is unclear, you can query the full code of the binding:

 1//<summary> 2///Get all information from users 3//</summary> 4//<returns></re  Turns> 5 public ActionResult Getalluserinfo () 6 {7 int pageIndex = request["page"] = = NULL ? 1:int. Parse (request["page"]); 8 int pageSize = request["Rows"] = = null? 10:int. Parse (request["Rows"]);                 9 int total = 0;10 using (easyuidemodbentities db = new Easyuidemodbentities ()) 11 {12 var temp = from u in db. UserInfo Select u;13 Total = temp. Count (); var users = temp. OrderByDescending (s = s.id) 15. Skip<userinfo> ((pageIndex-1) * pageSize). Take<userinfo> (pageSize); var data = new17 {total = total,1 9 rows = Users. Tolist<userinfo> ()};21 return Json (data); 22}23}

Effect:

Add, modify, and delete data

This simple example server has only one context, the following is a new example, the modification of the deletion is similar operation, download to see the full code, new user operation front-end code:

 1 @* Add user pop-up window *@ 2 <div id= "Adduserdialog" class= "Easyui-dialog" style= "width:360px;height:310px;padding:10px 20px "3 closed=" true "resizable=" true "modal=" true "buttons=" #dlg-buttons "align=" Center "> 4 <form I                     d= "FF" method= "POST" novalidate= "Novalidate" > 5 <table id= "Tbladd" > 6 <tr> 7 <td><label for= "name" > Username:</label></td> 8 <td><inpu T class= "Easyui-validatebox" type= "text" id= "name" name= "name" data-options= "Required:true,validtype: ' length[1,32] ' "/></td> 9 </tr>10 <tr>11 <td><label fo R= "Password" > Password: </label></td>12 <td><input class= "Easyui-validatebox" type= "Te                 XT "Id=" Password "name=" Password "data-options=" Required:true,validtype: ' length[1,32] ' "/></td>13                </tr>14     <tr>15 <td><label for= "Passwordok" > Confirm password: </label></td>16 <td><input class= "Easyui-validatebox" type= "text" id= "Passwordok" name= "Passwordok" data-options= "Requir                     Ed:true "validtype=" equalto[' Password '] "invalidmessage=" two times input password mismatch "/></td>17 </tr>18                     <tr>19 <td><label for= "Phone" > Tel: </label></td>20 <td><input class= "Easyui-numberbox" type= "text" id= "phone" name= "Phone" data-options= "Validtype: ' Leng TH[1,14] ' "/></td>21 </tr>22 <tr>23 <td>&lt Label for= "Mail" > Email:</label></td> <td><input class= "Easyui-validatebox" t Ype= "text" id= "Mail" name= "Mail" data-options= "required:true,validtype: ' email '"/></td>25 </tr >26 &Lt;tr>27 <td><label for= "Address" > Add: </label></td>28 &l T;td><textarea id= "Address" name= "Address" style= "height:50px;" ></textarea></td>29 </tr>30 <tr>31 &LT;TD&G T;<label for= "Enable" > Enable: </label></td>32 <td><select id= "Enable" Name= "Enab Le "class=" easyui-combobox "panelheight= ' auto ' >33 <option value=" 1 "> Enable </option>                     <option value= "0" > Forbidden </option>35 </select>36 </td>37 </tr>38 <tr>39 <td colspan = "2" style= "text-align:center; padding-top:10px ">40 <a href=" javascript:void (0) "class=" Easyui-linkbutton "id=" Btnadduser "          iconcls= "Icon-ok" > OK </a>41               <a href= "javascript:void (0)" class= "Easyui-linkbutton" iconcls= "Icon-cancel" onclick= "javascript:$ (' #Add             Userdialog '). Dialog (' Close ') ' > Close </a>42 </td>43 </tr>44 </table>45 </form>46 </div>

JS Code:

 1//Add User dialog box 2 function Adduserdialog () {3 $ (' #AddUserDialog '). Dialog (' Open '). Dialog (' Settitl E ', ' Add user '); 4 cleartext (); 5} 6//Add user Add Event 7 function bindadduserclickevent () {8 $ ("#btnAddUser"). Click (functio  N () {9//Verify that all text boxes are verified by the user of the ten var valid = $ (' #ff '). Form (' Validate '); (valid = = False) {return false;13}14 var cbenable = true;15 if ($ (" #Enable "). ComboBox (' getValue ') = =" 0 ") {cbenable = false;17}18 19// To create a passed parameter, var postdata = {$ Name: $ ("#Name"). Val (), Password: $                     ("#Password"). Val (), at $ ("#Mail"). Val (), $ ("#Phone"). Val (), 25   Address: $ ("#Address"). Val (), Enable:cbenable27              };28 29//Send asynchronous request to background save user data $.post ("/user/adduser", PostData, function (data {if (data = = "OK") {alert ("Add Success"); $ (' #AddUs                     Erdialog '). Dialog (' Close '); $ ("#test"). DataGrid ("Reload"); 35}36             else {PNS alert ("Add failed, please check"); 38}39}); 40 }); 41}

Controller code:

1//         <summary> 2//         Add user 3//         </summary> 4//         <param name= "UserInfo" ></param > 5         //<returns></returns> 6 public         actionresult AddUser (UserInfo UserInfo) 7         {8             UserInfo. Createtime = DateTime.Now; 9             using (easyuidemodbentities db = new Easyuidemodbentities ()) Ten             {one                 db. Userinfo.add (UserInfo),                 db. SaveChanges ();             }14             return Content ("OK");         

Can see the front end of the Adduserdialog is a add User pop-up window, which is the main note is some Easyui control value or assignment operations, such as the ComboBox value is: $ ("#Enable1"). ComboBox (' GetValue '); The assignment is: $ (' #Enable '). ComboBox (' SetValue ', ' 1 '); These are small operations that take a long time to take. You can see the Easyui is very convenient to use, maybe JS script needs to write something, but the page layout is very simple. Controller there is only one context operation, there is no encapsulation, for like side dishes we are a welfare, after all, the road is 1.1 points out.

, complete sample Demo download

Full sample demo Download: Http://pan.baidu.com/s/1i3kMyzV

Postscript

The above example demo may be very simple for many people, but if you do it by yourself, you will find that there will be a lot of things to learn, sometimes above his business to do something, but the reverse is really thought highly yourself. Of course, this demo has a lot of questions to be perfected, is still in the study, with you to encourage.

If you think this article will help you, please click "Recommend" in the lower right, ^_^

Easyui Reference Sample Tutorial:

    • Http://www.cnblogs.com/xishuai/p/3620327.html

Easyui+mvc+ef Simple User Management demo (problem and resolution)

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.