MVC - 调用外部Web服务并在视图中显示它

时间:2014-01-13 21:26:26

标签: c# asp.net-mvc

我是asp.net MVC的新手。我手头的任务是联系Web服务调用其方法之一并在视图中显示它。我已经开始创建一个新的MVC2应用程序。在VS2010。这是我的index.aspx(默认页面)视图:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: ViewData["Message"] %></h2>
<p>
    <fieldset>
    <legend>Create Soap Request</legend>
@using (Ajax.BeginForm("CreateSoapRequestResult","CreateSoapRequest",
                        new AjaxOptions { UpdateTargetId = "divSoapRequestDetails" }))
{
    <div id="divSoapRequestDetails"></div>
    <ol>
        <li>
            @Html.Label("Method")
            @Html.TextBox("txtMethodName")
        </li>
        <li>
            @Html.Label("Username")
            @Html.TextBox("txtUsername")
        </li>
        <li>
            @Html.Label("Password")
            @Html.TextBox("txtPassword")
        </li>
    </ol>
<button>Generate Request</button>
}   
</fieldset>
</p>
</asp:Content>

但我最终想知道如何传递数据。我假设我需要将它传递给控制器​​(或模型),然后创建soap请求,调用服务方法并获得响应。如果我错了,请纠正我。然后我必须以另一种观点(最好)呈现它。

1 个答案:

答案 0 :(得分:1)

你应该保持简单:

#1)  Create a model that contains ALL the data elements for your view, this is called a ViewModel.  This model goes in the "Models" folder in your MVC App.
#2)  Call the Web Service  from your controller, if you're fluent in c# this wont be a problem.
#3)  Change your view to work with the model.  use the @model attribute in the view.

在您的控制器中:

public ActionResult Index()
{

    ViewModel vm = new ViewModel();   // <-- obviously this is named as an example
    WebService.Service = ws = new WebService.Service();
    string name = ws.GetName();

    vm.Name = name;
    return View("Index", vm);

}

在您看来:

@model ViewModel
. . . 
rest of html/razor.