Catalog

【 Chapter one 】ASP.NET MVC Quick start of database operation (MVC5+EF6)

【 Second articles 】ASP.NET MVC Quick start data annotation (MVC5+EF6)

【 Third articles 】ASP.NET MVC Quick start security policy (MVC5+EF6)

【 Fourth articles 】ASP.NET MVC A complete example of getting started (MVC5+EF6)

【 Set pieces 】ASP.NET MVC Quick start is free jQuery Control library (MVC5+EF6)

FineUIMvc brief introduction

FineUIMvc  Is based on  jQuery  Major of  ASP.NET MVC  Control library , Its predecessor is based on  WebForms  Open source control library based on  FineUI( after 9 year 120 Multiple versions ).FineUIMvc( Basic Edition ) Contains all the features of the open source version , Support  30  A built-in theme and  FontAwesome  Icon , Support message dialog box and cell edit table , Powerful , Most importantly, it's completely free .

Here's a quote from FineUI Introduction to the official website :

FineUIMvc( Basic Edition ) As a gift from Sanshi to the community , It's absolutely powerful enough to make your heart beat :

1.       Have FineUI( Open source Edition ) All the functions of .

2.       Have FineUI( pro ) same jQuery Front end Library , Small volume , Fast .

3.       Have FineUIMvc( Enterprise Edition ) Powerful notification dialog and cell edit table .

4.       built-in 30 Kind of Metro and jQueryUI The theme ( And custom themes Bootstrap Pure).

5.       built-in 500 Multiple FontAwesome Icon Font , Control native support .

6.       9 Annual technology accumulation ,1300 A number of donor members ,100 Multiple corporate customers , Stable and reliable .

7.       Important things are to be repeated for 3 times : Completely free ! Completely free ! Completely free !

Website home page :http://fineui.com/mvc/
Online example :http://fineui.com/demo_mvc/

This article , We will use FineUIMvc( Basic Edition ) To implement this example .

FineUIMvc Empty item

Sign in FineUI The BBS , download FineUIMvc Empty item , This not only saves the configuration trouble , And there is the default implementation of the left and right framework :

http://fineui.com/bbs/forum.php?mod=viewthread&tid=9101

double-click FineUIMvc.EmptyProject.sln, Open the project :

This directory structure is very similar to the previous one , One more. res Catalog , This is FineUIMvc The agreement in , Used to place static resources , such as CSS、JS、 Pictures and a set of Icon Icon .

Ctrl+F5 Run the project directly :

modify Web.config

The empty project has been configured Web.config file , There are mainly two changes :

<configSections>
<section name="FineUIMvc" type="FineUIMvc.ConfigSection, FineUIMvc"
requirePermission="false" />
</configSections>
<FineUIMvc DebugMode="true" Theme="Cupertino" />

Set up here FineUIMvc Global parameters of :

l  Theme: Style theme , built-in 30 Themes ( among 6 Kind of Metro The theme ,24 Kind of jQueryUI Official theme , The default value is :Default)

n  Metro The theme :Default, Metro_Blue, Metro_Dark_Blue, Metro_Gray, Metro_Green, Metro_Orange

n  jQueryUI The theme : Black_Tie, Blitzer, Cupertino, Dark_Hive, Dot_Luv, Eggplant, Excite_Bike, Flick, Hot_Sneaks, Humanity, Le_Frog, Mint_Choc, Overcast, Pepper_Grinder, Redmond, Smoothness, South_Street, Start, Sunny, Swanky_Purse, Trontastic, UI_Darkness, UI_Lightness, Vader

l  CustomTheme: Custom style theme (custom_default/bootstrap_pure)

l  Language: Control language (en/zh_CN/zh_TW, The default value is :zh_CN)

l  FormMessageTarget: The display position of the form field error message (Title/Side/Qtip, The default value is :Side)

l  FormLabelWidth: The width of the form field label ( The default value is :100px)

l  FormLabelAlign: The location of the form field label (Left/Right/Top, The default value is :Left)

l  FormRedStarPosition: The position of the red asterisk in the form field (AfterText/BeforeText/AfterSeparator, The default value is :AfterText)

l  FormLabelSeparator: The separator between the label and the content of the form field ( The default value is :":")

l  EnableAjax: Is it enabled? AJAX( The default value is :true)

l  AjaxTimeout: Ajax Timeout time ( Company : second , The default value is :120s)

l  DebugMode: Whether the development mode , Format page output when enabled JavaScript Code , Easy to debug ( The default value is :false)

l  EnableAjaxLoading: Is it enabled? Ajax Tips ( The default value is :true)

l  AjaxLoadingType: Ajax Type of tip , By default, the Yellow prompt box is displayed at the top of the page (Default/Mask, The default value is :Default)

l  EnableShim: Whether the mask layer is enabled , prevent ActiveX、Flash And so on ( The default value is :false)

l  EnableCompactMode: Compact mode enabled or not ( The default value is :false)

l  EnableLargeMode: Whether to enable large font mode ( The default value is :false)

l  MobileAdaption: Whether to enable mobile browser adaptation ( The default value is :false)

l  EnableAnimation: Whether animation is enabled ( only Webkit The browser supports animation effects )( The default value is :false)

l  LoadingImageNumber: The page loads the serial number of the animated picture ( from 1 To 30, The default value is :1)

More detailed introduction reference FineUIMvc Online sample sites :

http://mvc.fineui.com/#/Config/ModifyWebConfig

Another configuration HTTP processor :

<system.web>
<httpModules>
<add name="FineUIMvcScriptModule" type="FineUIMvc.ScriptModule, FineUIMvc"/>
</httpModules>
<httpHandlers>
<add verb="GET" path="res.axd" type="FineUIMvc.ResourceHandler, FineUIMvc"/>
</httpHandlers>
</system.web>

If you used it before FineUI( Open source Edition ), I believe I am familiar with this configuration .

Add global model binder

stay Global.asax in , Add all model binders :

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes); ModelBinders.Binders.Add(typeof(JArray), new JArrayModelBinder());
ModelBinders.Binders.Add(typeof(JObject), new
JObjectModelBinder());
}

This setting is used for model binding , The client can pass in JSON The array is automatically converted to JArray object , Similar to the following code :

Of course, this setting is not necessary , If you remove this setting , The above code needs to be written like this :

public ActionResult Grid1_PageIndexChanged(string Grid1_fields, int Grid1_pageIndex)
{
JArray fields = JArray.Parse(Grid1_fields); // .....
}

Layout view

The layout view is similar to WebForms The master page of , be located Views/Home/Shared/_Layout.cshtml, Let's look at the code first :

@{
var F = Html.F();
} <!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title - FineUIMvc Empty item </title> @F.RenderCss()
<link href="~/res/css/common.css" rel="stylesheet" type="text/css" />
@RenderSection("head", false) </head>
<body>
@Html.AntiForgeryToken() @F.PageManager @RenderSection("body", true) @F.RenderScript()
@RenderSection("script", false) </body>
</html>

The overall architecture is very simple , Among them FineUIMvc Closely related code :

1.     var F = Html.F(): Instantiation FineUIMvc Of HTML Auxiliary method , All of the FineUIMvc Control must pass F Variable to initialize .

2.     F.RenderCss(): place FineUIMvc Built in CSS file .

3.     F.PageManager:FineUIMvc Page manager for , Every page needs , So put it in the layout view .

4.     F.RenderScript(): place FineUIMvc Built in JavaScript file .

besides , We also passed MVC Built in RenderSection Function defines several paragraphs , It's mainly used to place custom CSS file , Page body HTML And page customization JavaScript Script files .

Html.AntiForgeryToken() Used to prevent cross site request forgery attack , It needs to cooperate with the method in the controller [ValidateAntiForgeryToken] Use of features , The third article in this series gave a detailed introduction .

Be careful : Harmony VS There's a big difference in automatically generated layout views , Use here RenderSection("body", true) Come to the way of the subject HTML, The second parameter true It shows that this is a required option . So on the specific view page , There has to be something called body The festival of , Otherwise you will report an error .

Home view

The code of the home page view is a bit complicated , You can see from the screenshot that , The whole page is divided into three parts , Place the URL title in the top half , Operate buttons and other controls , On the left is a tree control , On the right is a tab control , Let's look at the code in this part first :

@(F.RegionPanel()
.ID("RegionPanel1")
.ShowBorder(false)
.IsViewPort(true)
.Regions(
F.Region()
.ID("Region1")
.ShowBorder(false)
.ShowHeader(false)
.RegionPosition(Position.Top)
.Layout(LayoutType.Fit)
.ContentEl("#header"),
F.Region()
.ID("Region2")
.RegionSplit(true)
.Width()
.ShowHeader(true)
.Title(" menu ")
.EnableCollapse(true)
.Layout(LayoutType.Fit)
.RegionPosition(Position.Left)
.Items(
F.Tree()
.ShowBorder(false)
.ShowHeader(false)
.ID("treeMenu")
.Nodes(
F.TreeNode()
.Text(" Default category ")
.Expanded(true)
.Nodes(
F.TreeNode()
.Text(" Start page ")
.NavigateUrl("~/Home/Hello"),
F.TreeNode()
.Text(" The login page ")
.NavigateUrl("~/Home/Login")
)
)
),
F.Region()
.ID("mainRegion")
.ShowHeader(false)
.Layout(LayoutType.Fit)
.RegionPosition(Position.Center)
.Items(
F.TabStrip()
.ID("mainTabStrip")
.EnableTabCloseMenu(true)
.ShowBorder(false)
.Tabs(
F.Tab()
.ID("Tab1")
.Title(" home page ")
.BodyPadding()
.Layout(LayoutType.Fit)
.Icon(Icon.House)
.ContentEl("#maincontent")
)
)
)
)

The outermost layer is a RegionPanel Control , And set to fill the entire browser window (IsViewPort=true), The upper part of Region Control through ContentEl Property to specify a id=header Of HTML fragment ; left Region There's a hard coded Tree Control , By designation Region Of Layout=Fit To make the Tree Control fills the entire left area ; On the right side Region There is... In it TabStrip Control ,TabStrip An initial tab is placed Tab, And pass ContentEl To point to a id=maincontent Of HTML fragment .

This analysis process is also easy to understand , If you have used FineUI( Open source Edition ), Contrast should be no stranger , It's just that the previous ASPX The grammar changed to Rezor It's just grammar .

The interaction between the left tree control and the right tab control is controlled by JavaScript Code controlled , This common interaction FineUIMvc It was packaged :

@section script {
<script>
// After initializing the page control , Will call the user-defined onReady function
F.ready(function () { // Initialize tree and tab interaction in the main frame , And the update of the address bar
// treeMenu: Tree control instance in the main frame
// mainTabStrip: Tab instance
// updateHash: Switch Tab when , Update address bar Hash value ( The default value is :true)
// refreshWhenExist: When adding a tab , If the tab already exists , Whether to refresh the internal IFrame( The default value is :false)
// refreshWhenTabChange: When switching tabs , Whether to refresh the internal IFrame( The default value is :false)
// maxTabCount: The maximum number of tabs allowed to open
// maxTabMessage: When the maximum number of open tabs is exceeded
F.initTreeTabStrip(F.ui.treeMenu, F.ui.mainTabStrip, {
maxTabCount: 10,
maxTabMessage: ' Please close some tabs first ( The maximum allowed is 10 individual )!'
}); });
</script>
}

Yes, there are JavaScript A simple description of the code :

1.     F.ready: Execute after the control is initialized , Be similar to jQuery Of $.ready, It's just F.ready Is in DomReady After that .

2.     F.initTreeTabStrip: Set the interaction between tree control and tab control , Click the tree control node to create a new one IFrame Tab control for . There are many parameters that can control the interaction behavior , There are comments in the code above , It's not going to be explained one by one .

3.     F.ui.treeMenu: Reference the tree control instance on the left .FineUIMvc Will be in F.ui Named controls store all pages initialized on FineUIMvc Control , Therefore, it is convenient to refer to through the name of the control .

Topic selection box

There's another need for this page JavaScript Script interaction process , That's in the top right corner of the page [ Main warehouse ] Button , When you click this button, an enable IFrame Of Window Control , Default this Window Control is hidden :

@(F.Window()
.Hidden(true)
.EnableResize(true)
.EnableMaximize(true)
.EnableClose(true)
.Height(600)
.Width(1020)
.IsModal(true)
.ClearIFrameAfterClose(false)
.IFrameUrl(Url.Content("~/Home/Themes"))
.EnableIFrame(true)
.Title(" Theme warehouse ")
.ID("windowThemeRoller")
)

The code for the button is placed in id=header Of HTML In the clip :

@(F.Button()
.EnableDefaultCorner(false)
.EnableDefaultState(false)
.IconFont(IconFont.Bank)
.IconAlign(IconAlign.Top)
.Text(" Theme warehouse ")
.ID("btnThemeSelect")
.CssClass("icontopaction themes")
.Listener("click", "onThemeSelectClick")
)

adopt Button Of Listener Property to specify what to do when you click the button JavaScript Script :

// Click on the theme Repository 
function onThemeSelectClick(event) {
F.ui.windowThemeRoller.show();
}

The logic of choosing a topic is also very simple , Save the user selected value to Cookie And then refresh the page , This logic is not difficult , Please check the source code yourself .

After page refresh , How to go from Cookie Read the value in and set the required theme ? This logic is actually done in the layout view , Let's take a look at the complete layout view :

@{
var F = Html.F();
} <!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title - FineUIMvc Empty item </title> @F.RenderCss()
<link href="~/res/css/common.css" rel="stylesheet" type="text/css" />
@RenderSection("head", false) </head>
<body>
@Html.AntiForgeryToken() @{
var pm = F.PageManager; // The theme
HttpCookie themeCookie = Request.Cookies["Theme_Mvc"];
if (themeCookie != null)
{
string themeValue = themeCookie.Value;
Theme theme;
if (Enum.TryParse<Theme>(themeValue, true, out theme))
{
pm.CustomTheme(String.Empty);
pm.Theme(theme);
}
else
{
pm.CustomTheme(themeValue);
}
}
}
@F.PageManager @RenderSection("body", true) @F.RenderScript()
@RenderSection("script", false) </body>
</html>

This logic is not difficult , First of all, from the requested HTTP Parameter to read the required Cookie value , Then set the PageManager Of Theme attribute , The reason why there is a Enum.TryParse The logic of , Because Cookie You can also save user-defined themes in , The treatment of the two is different .

The login page

1.     Visit the student list page , Users will be required to log in first , If you enter... Directly in the browser address bar :

http://localhost:64475/Students

2.     The page will be redirected to :http://localhost:64475/Login?ReturnUrl=%2fStudents

3.     After successful login , The page will be redirected to the home page :

4.     At this point, click the drop-down menu item of the user's Avatar [ Safety exit ], Will be redirected to the login page .

This series of processes is complete through form authentication , Let's look at the view code of the login page first :

@{
ViewBag.Title = "Login";
var F = @Html.F();
} @section body {
@(F.Window()
.Width()
.WindowPosition(WindowPosition.GoldenSection)
.EnableClose(false)
.IsModal(false)
.Title(" login form ")
.ID("Window1")
.Items(
F.SimpleForm()
.ShowHeader(false)
.LabelWidth()
.BodyPadding()
.ShowBorder(false)
.ID("SimpleForm1")
.Items(
F.TextBox()
.ShowRedStar(true)
.Required(true)
.Label(" user name ")
.ID("tbxUserName"),
F.TextBox()
.ShowRedStar(true)
.Required(true)
.TextMode(TextMode.Password)
.Label(" password ")
.ID("tbxPassword")
)
)
.Toolbars(
F.Toolbar()
.Position(ToolbarPosition.Bottom)
.ToolbarAlign(ToolbarAlign.Right)
.ID("Toolbar1")
.Items(
F.Button()
.OnClick(Url.Action("btnLogin_Click"), "SimpleForm1")
.ValidateTarget(Target.Top)
.ValidateForms("SimpleForm1")
.Type(ButtonType.Submit)
.Text(" Sign in ")
.ID("btnLogin"),
F.Button()
.Type(ButtonType.Reset)
.Text(" Reset ")
.ID("btnReset")
)
)
)
}

This page is made up of several FineUIMvc Control :

1.     Window Control : The default pop-up Window Control in the middle of the page .

2.     Toolbar Control :Window Control's bottom toolbar .

3.     Button Control : In the toolbar [ Sign in ] and [ Reset ] Button .

4.     TextBox Control :[ user name ] and [ password ] Text input box .

Click on [ Sign in ] Button , To launch a HTTP POST request , This request corresponds to the controller Login Of btnLogin_Click Method , The second parameter SimpleForm1 Use to specify the form parameters used to pass in the controller method .

This process is very important for WebForms Developers should be familiar with it , If you use WebForms I can put it this way : Click on [ Sign in ] Button , Send back the current page , Trigger the background btnLogin_Click event . Here I specially keep WebForms The naming method of background events , In fact, the soup is not changed , All kinds of changes are inseparable from their ancestors , understand HTTP How the protocol works , It's not hard to understand .

Backstage btnLogin_Click Method :

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult btnLogin_Click(string tbxUserName, string tbxPassword)
{
if (tbxUserName == "admin" && tbxPassword == "admin")
{
FormsAuthentication.RedirectFromLoginPage(tbxUserName, false);
}
else
{
ShowNotify(" Wrong user name or password !", MessageBoxIcon.Error);
} return UIHelper.Result();
}

Exit operation :

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult onSignOut_Click()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Login");
}

Student list page (CRUD)

FineUIMvc All the servers in the POST Requests are all AJAX, So we can easily make single page applications . coordination FineUIMvc Built in IFrame Support , Some logic can be separated into a page , Not only does it help decouple the code , And the page effect is relatively uniform .

Student list home page :

In this page , We can do the following :

1.     New users : Pop up an enable IFrame Of Window Control , Add new users in the new page , After operation , You need to rebind the table data ( Because the data has changed ).

2.     Edit user : It's a similar logic to adding .

3.     Delete individual users : The delete button is integrated in the table row , There will be a confirmation prompt box before deleting .

4.     Delete multiple users : Click... In the form toolbar [ Delete the selected record ], You can delete multiple records at once , Also, there will be a confirmation prompt box before deleting .

Form page

Let's look at the view code of the table first :

@(F.Grid()
.IsViewPort(true)
.ShowHeader(false)
.ShowBorder(false)
.ID("Grid1")
.DataIDField("ID")
.DataTextField("Name")
.EnableCheckBoxSelect(true)
.Toolbars(
F.Toolbar()
.Items(
F.Button()
.ID("btnDeleteSelected")
.Icon(Icon.Delete)
.Text(" Delete the selected record ")
.Listener("click", "onDeleteSelectedClick"),
F.ToolbarFill(),
F.Button()
.ID("btnCreate")
.Icon(Icon.Add)
.Text(" New users ")
.Listener("click", "onCreateClick")
)
)
.Columns(
F.RowNumberField(),
F.RenderField()
.HeaderText(" full name ")
.DataField("Name")
.Width(),
F.RenderField()
.HeaderText(" Gender ")
.DataField("Gender")
.FieldType(FieldType.Int)
.RendererFunction("renderGender")
.Width(),
F.RenderField()
.HeaderText(" Major in ")
.DataField("Major")
.ExpandUnusedSpace(true),
F.RenderField()
.HeaderText(" Date of admission ")
.DataField("EntranceDate")
.FieldType(FieldType.Date)
.Renderer(Renderer.Date)
.RendererArgument("yyyy-MM-dd")
.Width(),
F.RenderField()
.HeaderText("")
.Width()
.RendererFunction("renderEditField")
.TextAlign(TextAlign.Center)
.EnableHeaderMenu(false),
F.RenderField()
.HeaderText("")
.Width()
.RendererFunction("renderDeleteField")
.TextAlign(TextAlign.Center)
.EnableHeaderMenu(false)
)
.DataSource(Model)
)

In addition to the definition of table columns , This is the definition of the toolbar at the top of the table , It contains two operation buttons as shown in the figure .

Table data is obtained through DataSource Method specified , Incoming Model Parameter types are defined in the page header :

@model IEnumerable<FineUIMvc.QuickStart.Models.Student>

Line rendering functions RendererFunction

Also note the gender column and the last two operation columns of the table , It's all defined RendererFunction Method , It is used to specify the client rendering script for the column . For the gender column , We know that the data type is int, So it needs to be converted to a string through the client render function :

function renderGender(value, params) {
return value == 1 ? ' male ' : ' Woman ';
}

And the two operation Columns , You need to return the HTML fragment :

function renderDeleteField(value, params) {
return '<a href="javascript:;" class="deletefield">
<img class="f-grid-cell-icon" src="@Url.Content("~/res/icon/delete.png")"></a>';
} function renderEditField(value, params) {
return '<a href="javascript:;" class="editfield">
<img class="f-grid-cell-icon" src="@Url.Content("~/res/icon/pencil.png")"></a>';
}

Delete the click event of the icon in the line

Let's see how to handle the click events of edit icon and delete icon in the script :

F.ready(function () {
var grid1 = F.ui.Grid1;
grid1.el.on('click', 'a.deletefield', function (event) {
var rowEl = $(this).closest('.f-grid-row');
var rowData = grid1.getRowData(rowEl); F.confirm({
message: ' Are you sure you want to delete the selected row data ?',
target: '_top',
ok: function () {
deleteSelectedRows([rowData.id]);
}
});
});
});

First, through F.ui.Grid1 To get an instance of the table on the page , and F.ui.Grid1.el It's a standard jQuery object , Represents the... Of this form on the page DOM Elements . And then through jQuery Of on Function to register click events for edit and delete icons .

In the delete event , adopt jQuery Of closest Function to get the table row where the edit icon is located , Then we call the table getRowData Method to get row data , You need to know the line of this line when you delete it ID. And then call F.confirm The confirmation dialog box will pop up , When the user clicks the confirm button in the confirmation dialog box , Delete (deleteSelectedRows function ).

The reason why we put deletion logic in deleteSelectedRows in , This is because it is also needed in batch deletion , So extraction is a public method :

function deleteSelectedRows(selectedRows) {
// Trigger background events
F.doPostBack('@Url.Action("Grid1_Delete")', {
'selectedRows': selectedRows,
'Grid1_fields': F.ui.Grid1.fields
});
}

Here we call FineUIMvc Packaged AJAX POST Method F.doPostBack( Be similar to WebForms Medium __doPostBack The name of ), The first parameter specifies the requested URL, The second parameter specifies the additional form parameters in the request .

Click event of edit icon in line

Because of the need in Window Control pop up new user page and edit user page , So we also need a hidden Window Control :

@(F.Window()
.ID("Window1")
.Width()
.Height()
.IsModal(true)
.Hidden(true)
.Target(Target.Top)
.EnableResize(true)
.EnableMaximize(true)
.EnableIFrame(true)
.IFrameUrl(Url.Content("about:blank"))
.OnClose(Url.Action("Window1_Close"), "Grid1")
)

Be careful : We are Window Control settings Target=Top attribute , Indicates that the form pops up in the top page , Not limited to the current page , This is FineUIMvc Built in features , And only for enabling IFrame Of Window The form is valid (EnableIFrame).

stay F.ready Function to register the click event of the edit icon :

grid1.el.on('click', 'a.editfield', function (event) {
var rowEl = $(this).closest('.f-grid-row');
var rowData = grid1.getRowData(rowEl); F.ui.Window1.show('@Url.Content("~/Students/Edit/")?studentId=' + rowData.id, ' Edit user ');
});

In editing events , Also get the current row data first , And then call F.ui.Window1.show Come on Window Control to display the edit page , The second parameter [ Edit user ] Appoint Window Control's title bar text .

Edit... In the form [ Close after save ] Button logic

Let's start with Edit View code :

@{
ViewBag.Title = "Edit";
var F = @Html.F();
} @model FineUIMvc.QuickStart.Models.Student @section body {
@(F.Panel()
.ID("Panel1")
.ShowBorder(false)
.ShowHeader(false)
.BodyPadding()
.AutoScroll(true)
.IsViewPort(true)
.Toolbars(
F.Toolbar()
.Items(
F.Button()
.Icon(Icon.SystemClose)
.Text(" close ")
.Listener("click", "F.activeWindow.hide();"),
F.ToolbarSeparator(),
F.Button()
.ValidateForms("SimpleForm1")
.Icon(Icon.SystemSaveClose)
.OnClick(Url.Action("btnEdit_Click"), "SimpleForm1")
.Text(" Close after save ")
)
)
.Items(
F.SimpleForm()
.ID("SimpleForm1")
.ShowBorder(false)
.ShowHeader(false)
.Items(
F.HiddenFieldFor(m => m.ID),
F.TextBoxFor(m => m.Name),
F.RadioButtonListFor(m => m.Gender)
.Items(
F.RadioItem()
.Text(" male ")
.Value(""),
F.RadioItem()
.Text(" Woman ")
.Value("")
),
F.TextBoxFor(m => m.Major),
F.DatePickerFor(m => m.EntranceDate)
.EnableEdit(false)
)
)
)
}

Let's shift our focus to two action buttons :

1.     [ close ] Button :Listener("click", "F.activeWindow.hide();"), Register for a period of time in this way JavaScript Script , Used to close the current IFrame In the active form .

2.     [ Close after save ] Button : This logic needs to be handled on the server side , Because we need to save the data on the server to the database first , Then you can close the currently active form .

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult btnEdit_Click([Bind(Include = "ID,Name,Gender,Major,EntranceDate")] Student student)
{
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges(); // Close this form ( Trigger the closing event of the form )
PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
} return UIHelper.Result();
}

The logic to close the active form is through PageContext.RegisterStartupScript Function to register a section of JavaScript Script to complete , If you have used FineUI( Open source Edition ), You must be very familiar with this function :

1.     ActiveWindow It represents the current activity Window Control , And the current script is Window The control of IFrame On the page .

2.     GetHidePostBackReference Used to get a script , First, close the currently active Window Control , Then the trigger Window The control of Close event . The naming here as like as two peas in the open source , I believe you will not be strange .

Delete multiple rows of records

There is one in the table toolbar [ Delete the selected record ] Button , The user can go through Ctrl perhaps Shift Choose multiple lines , Then click delete :

The logic of this pop-up confirmation box is completed on the client side , If no value is selected by default , Another prompt box will pop up :

First, in the view through Listener Property to register the client script handler for the button :

F.Button()
.ID("btnDeleteSelected")
.Icon(Icon.Delete)
.Text(" Delete the selected record ")
.Listener("click", "onDeleteSelectedClick")

Let's take a look at the script processing function :

function onDeleteSelectedClick(event) {
var grid1 = F.ui.Grid1; if (!grid1.hasSelection()) {
F.alert(' Please select at least one !');
return;
} var selectedRows = grid1.getSelectedRows();
F.confirm({
message: ' Are you sure you want to delete the selected &nbsp;<b>' + selectedRows.length + '</b>&nbsp; OK, data ?',
target: '_top',
ok: function () {
deleteSelectedRows(selectedRows);
}
});
}

There are pairs. FineUIMvc The client of API Interface call :

1.     hasSelection: Returns whether the table has selected rows .

2.     F.alert: Used to pop up a prompt box .

3.     getSelectedRows: Returns the array of rows selected in the table , Array elements are row ID( In the table definition by DataIDField identification ), This function also has an overload , If you pass in true Parameters , Then the returned table element is row data .

4.     F.confirm: Used to pop up a confirmation box ,target Used to specify the location of the pop-up , Because the current page is located in iframe in , So we want the confirmation box to pop up in the top window .

Form retrieval and database pagination

Limited to space , Form retrieval and database pagination will not be explained , Please check the source code yourself .

Summary

This example uses FineUIMvc( Basic Edition ) To implement the same sample function , But the page effect is more professional , More functions , All to the server POST Requests are all AJAX, and IFrame The built-in support of makes the interaction of the whole page easy and natural , You don't have to jump around , At the same time, it can keep the business logic code independent , Easy to maintain and update .

Download sample source code

【 Set pieces 】ASP.NET MVC Quick start is free jQuery Control library (MVC5+EF6) More articles about

  1. 【 Third articles 】ASP.NET MVC Quick start security policy (MVC5+EF6)

    Catalog [ Chapter one ]ASP.NET MVC Quick start of database operation (MVC5+EF6) [ Second articles ]ASP.NET MVC Quick start data annotation (MVC5+EF6) [ Third articles ]ASP.NET MVC Quick start security strategy ...

  2. 【 Chapter one 】ASP.NET MVC Quick start of database operation (MVC5+EF6)

    Catalog [ Chapter one ]ASP.NET MVC Quick start of database operation (MVC5+EF6) [ Second articles ]ASP.NET MVC Quick start data annotation (MVC5+EF6) [ Third articles ]ASP.NET MVC Quick start security strategy ...

  3. 【 Fourth articles 】ASP.NET MVC A complete example of getting started (MVC5+EF6)

    Catalog [ Chapter one ]ASP.NET MVC Quick start of database operation (MVC5+EF6) [ Second articles ]ASP.NET MVC Quick start data annotation (MVC5+EF6) [ Third articles ]ASP.NET MVC Quick start security strategy ...

  4. 【 Second articles 】ASP.NET MVC Quick start data annotation (MVC5+EF6)

    Catalog [ Chapter one ]ASP.NET MVC Quick start of database operation (MVC5+EF6) [ Second articles ]ASP.NET MVC Quick start data annotation (MVC5+EF6) [ Third articles ]ASP.NET MVC Quick start security strategy ...

  5. ASP.NET MVC Load in WebForms User control (.ascx)

    original text :ASP.NET MVC Load in WebForms User control (.ascx) The problem background The calendar in blog garden blog uses ASP.NET WebForms Calendar control for (System.Web.UI.WebControl ...

  6. ASP.NET MVC Show WebForm Web page or UserControl Control

    ASP.NET MVC Show WebForm Web page or UserControl Control Study and use ASP.NET MVC So long , Or right asp.net Not forget for a moment . Can it be in asp.net mvc To display aspx or user ...

  7. Not forget for a moment ,ASP.NET MVC Show WebForm Web page or UserControl Control

    Study and use ASP.NET MVC So long , Or right asp.net Not forget for a moment . Can it be in asp.net mvc To display aspx or user control Well ? This inspiration ( Not inspiration , It's just an idea ) It's from a book I wrote the other day ...

  8. ASP.NET MVC Enumeration type to LIST CONTROL Control

    in application , We often use drop-down boxes . multi-select . Radio and other similar controls , We can collectively call them List Control, They are all one type of control , The similarities are all made by binding and rendering data in the form of one or a group of key value pairs . this ...

  9. be based on jQuery Major of ASP.NET WebForms/MVC Control library !

    Catalog [ Chapter one ]ASP.NET MVC Quick start of database operation (MVC5+EF6) [ Second articles ]ASP.NET MVC Quick start data annotation (MVC5+EF6) [ Third articles ]ASP.NET MVC Quick start security strategy ...

Random recommendation

  1. LINUX View log below

    LINUX All my logs are in /var/log Under the table of contents :    Go to this file to see the directory details : The command to view a log : 1.cat messages You can view a log file . 2. To achieve real-time update , Can pass tail Command view ...

  2. IOS Development - Encapsulating the database sqlite3 Why choose FMDB

    Why use a third-party lightweight framework FMDB? FMDB It's a third-party framework for data storage , It is associated with SQLite And Core Data Comparison , There are many advantages . FMDB It's object-oriented , It uses OC It encapsulates SQLite Of C language ...

  3. hdu4418( probability dp + Gauss elimination )

    It should be an entry-level topic . But there are a few pits . 1. Just choose x The point that can be reached is guass The unknowns in . 2. m May be greater than n, So when constructing equations, the coefficients of unknowns cannot be directly equal to , want += 3. There seems to be something wrong with the title ,D by - ...

  4. avalon in require The implementation of the

    var plugins = { loader: function(builtin) { window.define = builtin ? innerRequire.define : otherDef ...

  5. + (void)load and + (void)initialize What's the use

    Both methods can initialize some classes . There are some small differences .+(void)load Methods as long as the engineering type is added , Compiled , And .m This method is implemented in , Will be called once , It is worth noting that subclasses that are not implemented will not be called , Even if the parent class implements ...

  6. TCP Protocol three handshakes

    TCP Analysis of protocol three handshake process TCP(Transmission Control Protocol) Transmission control protocol TCP Is the host to host layer transmission control protocol , Provide reliable connection service , Use three handshakes to establish a connection : ...

  7. ImageView And its subclasses ( 3、 ... and )

    example : Use QuickContactBadge Associated contacts      QuickContactBadge Inherited ImageView, So the essence of it is also pictures , It can also be done through android:src Property to specify the image he displays ...

  8. SparkMLib Naive Bayes classification of classification algorithm

    SparkMLib Naive Bayes classification of classification algorithm ( One ) Naive Bayes classification understanding Naive bayes method is a classification method based on bayes theorem and independent hypothesis of feature conditions . Simply speaking , Naive Bayes classifier assumes that each feature of the sample is not related to other features . for instance , ...

  9. Swift4.0 Array Detailed explanation

    Introduction to array Array (Array) Is an ordered set of elements of the same type , The set elements in an array are ordered , Can be repeated . stay Swift The array type in is Array, Is a generic collection . The array is divided into : Variable and immutable arrays , Separate use ...

  10. HDU Today

    HDU Today Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Su ...