標籤:servicestack mvc client 添加新聞
建立好服務後,我們就可以在MVC項目中使用這個服務,在使用這個服務之前,需要先確定一下它所在連接埠,只需要在SS項目上點右鍵,將其設定為啟動項目,然後運行一下SS項目,在瀏覽器地址欄,就可以看到這個服務的連接埠號碼,並且也能看到已經添加到其中的服務。(啟動並執行效果可以在001節中的看到,001節中的連接埠為59068。)
在MVC的Controller目錄下添加一個控制器NewsController.cs,在NewsController.cs中加入一個 Action, 用來顯示添加新聞的頁面
public ActionResult Create() { return View(); }
在Views目錄下添加目錄News,在News中建立檔案Create.cshtml,或者在控制器中代碼上點右鍵直接直接建立視圖頁,在Create.cshtml視圖中添加
<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資料
[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項目上點右鍵,選擇“調試-啟動新執行個體”,
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/54/7F/wKioL1SFGaLTjvNoAAPoad3w2T4734.jpg" title="啟動新執行個體.png" alt="wKioL1SFGaLTjvNoAAPoad3w2T4734.jpg" />
3 啟動MVC網站後,在添加新聞的頁面添加一條新聞測試,提交成功後,可以在資料庫中的Submission表中看到新增的資料
4 Submission表是在DataRepository的AddSubmission函數中通過 db.CreateTable<Submission>();自動建立的,不需要手工建立這個表
主要參考資料 : Getting Started with ASP.NET MVC, ServiceStack and Bootstrap
本文出自 “LifeStage” 部落格,請務必保留此出處http://soaop.blog.51cto.com/6164600/1587471
ServiceStack 項目執行個體 005 使用第一個服務功能 (在MVC項目中)