ServiceStack 项目实例 005 使用第一个服务功能 (在MVC项目中)

    建立好服务后,我们就可以在MVC项目中使用这个服务,在使用这个服务之前,需要先确定一下它所在端口,只需要在SS项目上点右键,将其设置为启动项目,然后运行一下SS项目,在浏览器地址栏,就可以看到这个服务的端口号,并且也能看到已经添加到其中的服务。(运行的效果可以在001节中的截图看到,001节中的端口为59068。)

 

     在MVC的Controller目录下添加一个控制器NewsController.cs,在NewsController.cs中加入一个 Action, 用来显示添加新闻的页面

 

     

1

2

3

4

public ActionResult Create()

        {

            return View();

        }

 

      在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();

        }

     

    运行测试:

      将SS项目设置为启动项目,运行项目启动服务,

      启动服务后,在MVC项目上点右键,选择“调试-启动新实例”,

     ServiceStack 项目实例 005 使用第一个服务功能 (在MVC项目中)

 

    启动MVC站点后,在添加新闻的页面添加一条新闻测试,提交成功后,可以在数据库中的Submission表中看到新增的数据

     Submission表是在DataRepository的AddSubmission函数中通过 db.CreateTable<Submission>();自动创建的,不需要手工建立这个表

转载于:https://my.oschina.net/dingliu/blog/754158