Controller and Apicontroller in ASP. 4 Read, add, update, delete (CRUD)

Source: Internet
Author: User

The WebApi (Apicontroller) is more suitable for data processing and delivery in the ASP. NET MVC 4 architecture, while the MVC 4 Web (Controller) compares to the view layer data display to make a different move, this time if the Apico Ntroller and Controller cut out, then the two parts of the communication will be used very often. If you are using the MVVM architecture, in the Model-view View-model these two paragraphs, if a page to collect some data tables of some information, that in the View section must communicate with WebApi multiple times to the data, and associated data, it is more complex, another point, if the individual WebApi Url is written on the page, there may be a risk of security, because WEBAPI is open data, if not everyone can access, then you can not play the schema of MVVM.

Between the API and the view in the card a Controller or a WebApi, do a data relay station, the data collected at once to the view, and the view received data only need to split the data into the various fields. Finally to submit the whole package back to Model is the same in the Controller or WEBAPI after the analysis of authentication and then dispersed to the various APIs, so the security will greatly improve.

So this article explains how to do read, add, update, delete (CRUD) actions on the Controller to WebApi.

1. In Basecontroller (if no basecontroller is written in the controller) inherit Apicontroller or controller, then build several variables:

public class Baseapicontroller:apicontroller {    protected defaultconnection db = new defaultconnection ();//Database connection 
   protected HttpClient client;    protected httpresponsemessage response;    Public Baseapicontroller ()    {        client = new HttpClient ();        Client. baseaddress = new Uri ("Api Url");}    }

2. At this time in the Controller can be asynchronous to obtain the results of WEBAPI, before the return value to add async, and the return value to be wrapped with a Task, indicating that this is a numeric value is the result of the asynchronous, before receiving the value end to add the await prefix reference, Indicates that the execution method is paused until the waiting work is completed. So in the program to reference the reference:

Using System.Threading.Tasks;

In the next asynchronous get back Json string to be converted into the category form, need to use the method of JsonConvert, so to download Json.NET plugin in NuGet:




References in the program should be referenced again:

Using newtonsoft.json;using Newtonsoft.Json.Linq;

3. Complete the program code in the Function of Index:

Public async task<actionresult> Index () {    response = await client. Getasync ("api/rms/companyapi/");    String t_s = await response. Content.readasstringasync ();    var rms_company = jsonconvert.deserializeobject<list<rms_company>> (t_s);    Return View (Rms_company);}

Complete the program code in the Details Function:

Public async task<actionresult> Details (Guid? id = null) {    response = await client. Getasync ("api/rms/companyapi/" + ID);    String t_s = await response. Content.readasstringasync ();    var rms_company = jsonconvert.deserializeobject<rms_company> (t_s);    if (Rms_company = = null)    {        return httpnotfound ();    }    Return View (Rms_company);}

Complete program code in the Function of Create:

[HttpPost] [Validateantiforgerytoken]public async task<actionresult> Create (Rms_company rms_company) {    if ( Modelstate.isvalid)    {        setcontent (Jsonconvert.serializeobject (Rms_company));        Response = await client. Postasync ("Api/rms/companyapi", content);        Db. Rms_company.add (rms_company);        Db. SaveChanges ();        Return redirecttoaction ("Index");    }    Return View (Rms_company);}

Complete the program code in the Function of Edit:

Public async task<actionresult> Edit (Guid? id = null) {//Rms_company Rms_company = db.    Rms_company.find (ID); Response = await client.    Getasync ("api/rms/companyapi/" + ID); String t_s = await response.    Content.readasstringasync ();    var rms_company = jsonconvert.deserializeobject<rms_company> (t_s);    if (Rms_company = = null) {return httpnotfound (); } return View (Rms_company);} [HttpPost] [Validateantiforgerytoken]public async task<actionresult> Edit (Rms_company rms_company) {if ( Modelstate.isvalid) {Rms_company.        Updater = Guid.NewGuid (); Rms_company.        Updateon = DateTime.Now;        SetContent (Jsonconvert.serializeobject (Rms_company)); Response = await client.        Putasync ("api/rms/companyapi/" + rms_company.companyid, content); Db. Entry (Rms_company).        state = entitystate.modified; Db.        SaveChanges ();    Return redirecttoaction ("Index"); } return View (Rms_company);}

Complete program code in the Function of Delete:

Public async task<actionresult> Delete (Guid? id = null) {    //Rms_company Rms_company = db. Rms_company.find (ID);    Response = await client. Getasync ("api/rms/companyapi/" + ID);    String t_s = await response. Content.readasstringasync ();    var rms_company = jsonconvert.deserializeobject<rms_company> (t_s);        if (Rms_company = = null)    {        return httpnotfound ();    }    Return View (Rms_company);} [HttpPost, ActionName ("Delete")] [Validateantiforgerytoken]public async task<actionresult> deleteconfirmed (Guid ID) {    //Rms_company Rms_ Company = db. Rms_company.find (ID);    Response = await client. Deleteasync ("api/rms/companyapi/" + ID);    Db. Rms_company.remove (rms_company);    Db. SaveChanges ();    Return redirecttoaction ("Index");}

Controller and Apicontroller in ASP. 4 Read, add, update, delete (CRUD)

Related Article

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.