【问题标题】:Consume Restful WCF service in asp.net mvc 4 application在 asp.net mvc 4 应用程序中使用 Restful WCF 服务
【发布时间】:2015-04-02 08:48:19
【问题描述】:

我对 asp.net mvc 完全陌生。我在 asp.net mvc4 应用程序中使用 REST 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 始终为空,并且在我在文本框中输入我的 jsonstring 之前执行 Index() 方法。请问怎么解决这个问题

【问题讨论】:

  • 然后将传递给服务的 Textbox 和 id 的值是什么?
  • 我希望用户在文本框中输入一个字符串,该字符串将作为id调用服务方法GetRuleDetail

标签: c# asp.net wcf rest asp.net-mvc-4


【解决方案1】:

这不是正确的方法,首先您需要呈现一个视图,然后将其与 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
}   

【讨论】:

  • 谢谢你的帮助,我真的很困惑。但是还有一个问题,我如何创建这个视图?通常是在 ActionResult 中单击鼠标右键。
  • 您可以点击 Views 文件夹,然后点击 Add View。
  • 抱歉这些愚蠢的问题。但我不明白如何将每个 ActionResult 与其视图相匹配?
  • 它会自动匹配动作名称和视图名称视图名称和动作名称必须相同,否则你也可以这样做 return View(viewname);
  • 所以我创建了 2 个视图。一个用于Index,一个用于GetServiceData,两者代码相同?
猜你喜欢
  • 1970-01-01
  • 2011-04-24
  • 2013-11-12
  • 2011-07-23
  • 1970-01-01
  • 2011-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多