Asp.net MVC 1.0 (5)-Action filter, updatemodel, modelbinder, Ajax, unit test (non-original)

Source: Internet
Author: User
Introduction

Asp.net MVC action filter, updatemodel, modelbinder, Ajax, unit test

Action filter-filter information at the Controller layer. How to Implement Custom Action Filter

Updatemodel-Automatically assigns values to attributes of an object based on parameters

Modelbinder-defines how to bind a model. defamodelmodelbinder implements imodelbinder, which can automatically assign parameters to the corresponding attributes of the object based on the name.

Ajax-use Ajax in Asp.net MVC

Unit Test-use unit test in Asp.net MVC

Example

1. demo of Action filter provided by Asp.net MVC

Filterdemocontroller. CS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

using MVC.Models;

Namespace MVC. Controllers
{
// Handleerror-jump to error. aspx when an exception occurs (first locate in the specified view folder and then find it in the shared folder)
// Web. config configuration is required-<customerrors mode = "on"/>
[Handleerror]
Public class filterdemocontroller: Controller
{
// Each filter has an order attribute, which is used to specify the execution sequence of the filter.

// [Nonaction]-the current method is a normal method and is not parsed as action

// [Acceptverbs (httpverbs)]-call the HTTP Method of this action
// The httpverbs enumeration members are as follows: httpverbs. Get, httpverbs. Post, httpverbs. Put, httpverbs. Delete, httpverbs. Head

        ProductSystem ps = new ProductSystem();

// Actionname ()-action name. Default Value: Same method name
[Actionname ("product")]

// Validateinput ()-equivalent to validaterequest of @ page, used to verify whether dangerous code exists in the request. Prevents XSS attacks. The default value is true.
[Validateinput (false)]
Public actionresult details (int id)
{
VaR Product = ps. getproduct (ID );

            return View("Details", product);
        }

// Validateantiforgerytoken ()-prevents csrf attacks (html. antiforgerytoken () must be used in the view page ()). Principle: generate a random string and write it into both cookie and den. When form is submitted to action, verify whether the two are equal and whether the submitted source is the site page (For details, refer to the source code of Asp.net MVC)
// Prevent SQL injection during SQL spelling: @ Parameter
[Validateantiforgerytoken ()]
Public actionresult validateantiforgerytokentest ()
{
Return content ("validateantiforgerytoken ");
}

// Outputcache ()-cache. Duration-Cache seconds. Varybyparam-None, *. Multiple parameters are separated by commas (,).
[Outputcache (duration = 10, varybyparam = "NONE")]
// [Outputcache (cacheprofile = "mycache")]-set the cache through the configuration file. See http://www.cnblogs.com/webabcd/archive/2007/02/15/651419.html
Public actionresult outputcachedemo ()
{
Return content (datetime. Now. tostring ("yyyy-mm-dd hh: mm: SS "));
}

        public ActionResult HandleErrorDemo()
        {
            throw new Exception("HandleErrorDemo");
        }

// Authorize ()-verify. Take the membership
[Authorize (users = "user")]
// [Authorize (roles = "role")]
// Request. isauthenticated-A bool value is returned to indicate whether the request has passed verification.
Public actionresult authorizedemo ()
{
Return content ("authorize ");
}

// Demo of Custom Action Filter
[Myfilter ()]
Public actionresult myfilterdemo ()
{
Return content ("myfilterdemo" + "<br/> ");
}
}
}

Implementation of Custom Action Filter

Myfilter. CS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Web.Mvc;

Namespace MVC
{
/** // <Summary>
/// Custom Action filter, which must inherit the actionfilterattribute
/// </Summary>
Public class myfilter: actionfilterattribute
{
Public override void onactionexecuting (actionexecutingcontext filtercontext)
{
Httpcontext. Current. response. Write ("onactionexecuting" + "<br/> ");
}

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            HttpContext.Current.Response.Write("OnActionExecuted" + "<br />");
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            HttpContext.Current.Response.Write("OnResultExecuting" + "<br />");
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            HttpContext.Current.Response.Write("OnResultExecuted" + "<br />");
        }
    }
}

 

Details. aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MVC.Models.Products>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Details
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <% Html.BeginForm("ValidateAntiForgeryTokenTest", "FilterDemo"); %>
    <%= Html.AntiForgeryToken() %>
   
        Details
    <p>
        <strong>ProductID:</strong>
        <%= Html.Encode(Model.ProductID) %>
    </p>
    <p>
        <strong>ProductName:</strong>
        <%= Html.Encode(Model.ProductName) %>
    </p>
    <p>
        <input type="submit" name="btnSubmit" value="submit" />
    </p>
    <% Html.EndForm(); %>
</asp:Content>

2. Apply the updatemodel demo

Updatemodelcontroller. CS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace MVC.Controllers
{
    public class UpdateModelController : Controller
    {
        public ActionResult Details(string name, int age)
        {
            User user = new User();

// Updatemodel () and tryupdatemodel ()-the system automatically assigns values to attributes of an object based on parameters.

Base. updatemodel (User); // an exception is thrown when an error occurs.
// Base. tryupdatemodel (User); // do not throw an exception when a failure occurs.

            ViewData.Model = user;

            return View();
        }
    }
}

Details. aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MVC.Controllers.User>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Details
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
   
        Details
    <p>
        <strong>UserId:</strong>
        <%= Model.ID %>
    </p>
    <p>
        <strong>Name:</strong>
        <%= Model.Name%>
    </p>
    <p>
        <strong>Age:</strong>
        <%= Model.Age%>
    </p>
</asp:Content>

3. Demonstrate what is modelbinder

Modelbindercontroller. CS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

Namespace MVC. Controllers
{
Public class modelbindercontroller: Controller
{
/** // <Summary>
/// The route or parameter is automatically assigned to the corresponding attribute of the object.
/// Do this Work Is the defaultmodelbinder that implements the imodelbinder interface.
/// </Summary>
Public actionresult details (User user)
{
Base. viewdata. Model = user;

// Modelstate-Save the model status, including the corresponding error information
If (! Base. modelstate. isvalid)
{
Foreach (VAR state in modelstate)
{
If (! Base. modelstate. isvalidfield (State. Key ))
Viewdata ["errormsg"] = state. Key + "/" + state. value. value. attemptedvalue + "<br/> ";
}
}

            return View();
        }
    }
}

Details. aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Details
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
   
        Details
    <% var model = ((MVC.Controllers.User)ViewData.Model); %>
    <p>
        <strong>UserId:</strong>
        <%= model.ID %>
    </p>
    <p>
        <strong>Name:</strong>
        <%= model.Name %>
    </p>
    <p>
        <strong>Age:</strong>
        <%= model.Age %>
    </p>
    <p>
        <strong>error:</strong>
        <%= ViewData["errorMsg"] %>
    </p>
</asp:Content>

4. Ajax demo

<P>
Ajax
       
<SCRIPT src = "http://www.cnblogs.com/Scripts/MicrosoftAjax.debug.js" type = "text/JavaScript"> </SCRIPT>
<SCRIPT src = "http://www.cnblogs.com/Scripts/MicrosoftMvcAjax.debug.js" type = "text/JavaScript"> </SCRIPT>
                      
<Br/>
       
<! -- Ajaxhelper brief -->
<% = Ajax. actionlink (
"Details page with productid 1 ",
"Details ",
"Product ",
New {id = 1 },
New ajaxoptions {updatetargetid = "ajax "}
)
%>
</P>
<Div id = "ajax"/>

5. Perform unit tests in

Productcontrollertest. CS

using MVC.Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting.Web;
using System.Web.Mvc;

using MVC.Models;
using System.Collections.Generic;

Namespace MVC. Tests
{
/** // <Summary>
/// This is the test class of productcontrollertest, which aims
/// Contains all productcontrollertest Unit Tests
/// </Summary>
[Testclass ()]
Public class productcontrollertest
{
Private testcontext testcontextinstance;

/** // <Summary>
/// Obtain or set the test context. The context provides
/// Related to the current test run and Function .
/// </Summary>
Public testcontext
{
Get
{
Return testcontextinstance;
}
Set
{
Testcontextinstance = value;
}
}

Additional test attributes # additional region test attributes
//
// You can also use the following attributes when writing a test:
//
// Use classinitialize to run the code before the first test in the running class
// [Classinitialize ()]
// Public static void myclassinitialize (testcontext)
//{
//}
//
// Use classcleanup to run the code after all tests in the class are completed
// [Classcleanup ()]
// Public static void myclasscleanup ()
//{
//}
//
// Use testinitialize to run the code before running each test
// [Testinitialize ()]
// Public void mytestinitialize ()
//{
//}
//
// Use testcleanup to run the code after each test is run
// [Testcleanup ()]
// Public void mytestcleanup ()
//{
//}
//
# Endregion

/** // <Summary>
/// Index test
/// </Summary>
// Todo: Make sure that the urltotest attribute specifies a URL pointing to the ASP. NET page (for example,
// Http: // default. aspx ). For Service It is necessary to execute a unit test on the device,
// Whether you want to test the page, Web Service, or WCF Service.
[Testmethod ()]
[Hosttype ("ASP. NET")]
[Aspnetdevelopmentserverhost ("C: \ MVC", "/")]
[Urltotest ("http: // localhost: 2005/")]
Public void indextest ()
{
Productcontroller target = new productcontroller (); // todo: Initialize to an appropriate value.
Int pageindex = 0; // todo: Initialize to an appropriate value.

            ViewResult actual;
            actual = target.Index(pageIndex) as ViewResult;

            Assert.AreNotEqual(actual.ViewData.Model as List<Products>, null);
        }
    }
}

 

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.