2014-01-13 36 views
0

我是asp.net MVC的新手。我手頭上的任務是聯繫一個Web服務調用其方法之一併將其顯示在視圖中。我已經開始創建一個新的MVC2應用程序。在VS2010中。這是我的Index.aspx(默認頁面)視圖:MVC - 調用外部Web服務並在視圖中顯示

<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> 

但我在束手無策試圖找出如何圍繞傳遞數據。我假設我需要將它傳遞給控制器​​(或模型),然後創建肥皂請求,調用服務方法並獲得響應。如果我錯了,請糾正我。然後我必須以另一種觀點(最好是)呈現它。

回答

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. 
+0

其實我是想從表單視圖中的數據傳遞。實際上,我並不像使用典型的服務引用那樣調用Web服務。我正在編寫一個請求響應代碼來獲取xml並將其放入輔助類中。我認爲將表單中的數據轉化爲控制器將是第一步。然後使用我的助手類來獲取響應,填充我的模型並將其顯示在視圖中。這是不是正確的做法。 – Sai

+0

它取決於,如果你在做MVC,那麼你的模型應該在控制器中處理,而不是在表單中處理。 –

+0

對不起,我想我錯了。我的意思是將表單數據傳輸到控制器。就像登錄表單一樣。假設我想建立一個登錄頁面。我如何獲得用戶名和密碼到控制器? – Sai