簡體   English   中英

在ASP.NET MVC 4應用程序中使用Restful WCF服務

[英]Consume Restful WCF service in asp.net mvc 4 application

我對asp.net mvc完全陌生。 我在使用asp.net mvc4應用程序中的其余Web服務時遇到麻煩。

這是服務的接口:

[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()方法。 我該如何解決

這不是正確的方法,首先需要渲染視圖,然后將其與ID一起發布到服務器,然后將其傳遞給服務。您需要創建一個將綁定到視圖的模型。

第一個渲染視圖

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
}   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM