2015-04-02 100 views
0

我是全新的asp.net mvc。我在使用asp.net mvc4應用程序中的其他Web服務時遇到了麻煩。在asp.net mvc 4應用程序中使用Restful WCF服務

這是服務的接口:

[ServiceContract] 
public interface IService1 
{ 
    [OperationContract] 
    [WebInvoke(Method = "POST", UriTemplate = "GetRuleDetail/{id}")] 
    string GetRuleDetail(string id); 
} 

在我的MVC應用程序,我將我的服務作爲服務引用「ServiceReference1」

然後我創建了一個控制器:

public ActionResult Index() 
    { 
     string strjson = Request["Json"].ToString(); 
     //string strjson = "input={\"name\": \"obj1\",\"x\": 11,\"y\":20,\"obj\":{\"testKey\":\"val\",},\"tab\":[1 , 2, 46]}"; 
     ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client(); 
     return View(obj.GetRuleDetail(strjson)); 
    } 

字符串strjson,我想通過它從具有以下代碼的視圖:

@{ 
ViewBag.Title = "Index"; 
Layout = "~/Views/Shared/_Layout.cshtml";} <h2>Index</h2> <section class="contact"> 
<header> 
    <h3>Enter your JSON string</h3> 
</header> 
<p> 
    <ol> 
     <li> 
      @Html.Label("Json") 
      @Html.TextBox("txtJson") 
     </li> 
    </ol> 
</p> 
<p> 
    <button>Test</button> 
</p> 

我錯過了什麼嗎? Cz strjson始終爲null,並且在我在文本框中輸入jsonstring之前執行Index()方法。我該如何解決這個問題plz

+0

什麼將文本框的價值和id然後傳遞給服務的東西? – Mairaj 2015-04-02 09:00:36

+0

我希望用戶在文本框中輸入一個字符串,並將此字符串用作調用服務方法的id GetRuleDetail – 2015-04-02 09:03:51

回答

0

這是不正確的方法,首先你需要渲染一個視圖,而不是你將它發佈到服務器,然後將它傳遞給service.You需要創建一個模型,這將綁定查看。

首先渲染視圖

public ActionResult Index() 
{ 

    return View();//Tihs will simply return view 
} 

這是該視圖將綁定

public class JsonData 
{ 
    public string Id { get; set; } 
} 

這將是你的看法現在

@model JsonData 

@using (Html.BeginForm("GetServiceData", "ControllerName", FormMethod.Post)) 
{ 
     @Html.Label("Json") 
     @Html.TextBoxFor(m=>m.Id) 
     <input type="submit" value="Submit" /> 

} 

當你將在此視圖模型類它將與文本框中的數據一起發送到控制器

[HttpPost] 
public ActionResult GetServiceData(JsonData model) 
{ 
    ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client(); 
    return View(obj.GetRuleDetail(model.Id));//Tihs will simply return view 
} 
+0

感謝您的幫助,我非常困惑。 但還有一個問題,我如何創建這個視圖?通常這是在ActionResult內右鍵單擊。 – 2015-04-02 09:28:52

+0

您可以點擊Views文件夾並點擊Add View。 – Mairaj 2015-04-02 09:30:00

+0

對不起,這些愚蠢的問題。但我不明白如何將每個ActionResult匹配到它的視圖? – 2015-04-02 09:48:14

相關問題