創建好服務後,咱們就能夠在MVC項目中使用這個服務,在使用這個服務以前,須要先肯定一下它所在端口,只須要在SS項目上點右鍵,將其設置爲啓動項目,而後運行一下SS項目,在瀏覽器地址欄,就能夠看到這個服務的端口號,而且也能看到已經添加到其中的服務。(運行的效果能夠在001節中的截圖看到,001節中的端口爲59068。)html
在MVC的Controller目錄下添加一個控制器NewsController.cs,在NewsController.cs中加入一個 Action, 用來顯示添加新聞的頁面數據庫
1瀏覽器 2函數 3測試 4ui |
public ActionResult Create() spa { 3d return View(); 調試 } code |
在Views目錄下添加目錄News,在News中新建文件Create.cshtml,或者在控制器中代碼上點右鍵直接直接創建視圖頁,在Create.cshtml視圖中添加
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
< h2 >添加新聞</ h2 > < div > < form method = "POST" id = "newsStory" class = "reply" > < fieldset > < div class = "row" > < div class = "col-lg-4 col-md-4 col-sm-4 col-xs-12" > < label >標題: < span >*</ span ></ label > < input class = "form-control" id = "headline" name = "headline" type = "text" value = "" required = "" /> </ div > < div class = "col-lg-3 col-md-3 col-sm-3 col-xs-12" > < label >日期: </ label > < input class = "form-control" id = "date" name = "date" value = "" type = "text" /> </ div > </ div > < div class = "row" > < div class = "col-lg-12 col-md-12 col-sm-12 col-xs-12" > < label >內容: < span >*</ span ></ label > < textarea class = "form-control" id = "text" name = "text" rows = "3" cols = "40" required> </ textarea > </ div > </ div > </ fieldset > < button class = "btn-normal btn-color submit bottom-pad" type = "submit" >Send</ button > </ form > </ div > |
在NewsController.cs 中添加一個Action,接收上一個頁面的表單提交過來的數據,注意加上聲明
[HttpPost],指定接收POST數據
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
[HttpPost] public ActionResult Create(NewsStory newsStory) { try { var service = new JsonServiceClient( "http://localhost:59068/" ); service.Send<SubmissionResponse>( new Submission() { Body = newsStory.Text, Headline = newsStory.Headline, SubmissionTime = newsStory.Date }); } catch (Exception ex) { ViewBag.Message = ex.Message; } return View(); } |
運行測試:
1 將SS項目設置爲啓動項目,運行項目啓動服務,
2 啓動服務後,在MVC項目上點右鍵,選擇「調試-啓動新實例」,
![wKioL1SFGaLTjvNoAAPoad3w2T4734.jpg](http://static.javashuo.com/static/loading.gif)
3 啓動MVC站點後,在添加新聞的頁面添加一條新聞測試,提交成功後,能夠在數據庫中的Submission表中看到新增的數據
4 Submission表是在DataRepository的AddSubmission函數中經過 db.CreateTable<Submission>();自動建立的,不須要手工創建這個表