webapi 不用ajax 提交数据!

不想使用jQuery,全部以ASP.NET MVC来实现。Ok,那来看看,先来实现POST的功能,即是往Web API添加数据。

在控制器中,创建两个Action,即是视图Action,另一个是POST的Action:
技术分享

技术分享
HttpClient client = new HttpClient();

            HttpContent httpcontent = new StringContent(size.ToJson(), System.Text.Encoding.UTF8, "application/json");

            client.PostAsync("http://localhost:9001/api/size", httpcontent)
                .ContinueWith((postTask) =>
                {
                    postTask.Result.EnsureSuccessStatusCode();
                });
Source Code

 

视图代码:
技术分享

 

程序运行,看看是否能正常运行,数据库是否有数据插入?
技术分享

 

下面演示更新操作PUT,在控制器中,创建Action,一个显示数据,另一个更新数据:
技术分享

技术分享
 public ActionResult PutDemo(int id)
        {
            var sizes = ApiUtility.Get<Size>("http://localhost:9001/api/size/" + id);
            var model = sizes.FirstOrDefault();
            return View(model);
        }

        [HttpPost]
        public ActionResult PutDemo(Size size)
        {
            HttpClient client = new HttpClient();

            HttpContent httpcontent = new StringContent(size.ToJson(), System.Text.Encoding.UTF8, "application/json");

            client.PutAsync("http://localhost:9001/api/size", httpcontent)
                .ContinueWith((postTask) =>
                {
                    postTask.Result.EnsureSuccessStatusCode();
                });
            return RedirectToAction("PutDemo", size.Size_nbr);
        }
Source Code


视图:
技术分享

 
实时演示:
技术分享

 下面Insus.NET再把Delete的功能实现完,在实现删除这个功能时,出现一点点困难:
先在控制器创建操作Action:
技术分享

 

技术分享
public ActionResult DeleteDemo(int id)
        {
            var sizes = ApiUtility.Get<Size>("http://localhost:9001/api/size/" + id);
            var model = sizes.FirstOrDefault();
            return View(model);
        }

        [HttpPost]
        public ActionResult DeleteDemo(Size size)
        {
            HttpClient client = new HttpClient();

            client.DeleteAsync("http://localhost:9001/api/size/" + size.Size_nbr)
                .ContinueWith((postTask) =>
                {
                    postTask.Result.EnsureSuccessStatusCode();
                });
            return RedirectToAction("ShowApiData1");
        }
Source Code

 

看到否,在上图中的标记#2中,DeleteAsync方法,它是不接受一个复杂Complex对type。为了不需要对前些天的程序作过多的修改,因此Insus.NET只得对Web API进行修改。这也许是设计Web API时欠缺的思考。

posted @ 2017-09-09 23:58  抱天揽月  阅读(117)  评论(0)    收藏  举报