C# 在asp.net mvc 4应用程序中使用Restful WCF服务

C# 在asp.net mvc 4应用程序中使用Restful WCF服务,c#,asp.net,wcf,rest,asp.net-mvc-4,C#,Asp.net,Wcf,Rest,Asp.net Mvc 4,我对asp.NETMVC一无所知。在asp.net mvc4应用程序中使用rest web服务时遇到问题 这是服务的接口: [ServiceContract] public interface IService1 { [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "GetRuleDetail/{id}")] string GetRuleDetail(string id); } 在我的mvc应用

我对asp.NETMVC一无所知。在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>
@{
ViewBag.Title=“Index”;
Layout=“~/Views/Shared/_Layout.cshtml”}索引
输入JSON字符串

  • @Html.Label(“Json”) @Html.TextBox(“txtJson”)
  • 测验


    我错过什么了吗?Cz strjson始终为null,并且在文本框中输入jsonstring之前执行Index()方法。如何修复plz

    这不是正确的方法首先需要渲染视图,然后将其与id一起发布到服务器,然后将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" />
    
    }
    

    Textbox的值和将传递给服务的内容的id是什么?我希望用户在Textbox中输入一个字符串,这个字符串将用作调用服务方法GetRuleDetail的id谢谢您的帮助,我真的很困惑。但还有一个问题,我如何创建这个视图?通常是在ActionResult中单击鼠标右键。您可以单击“视图”文件夹,然后单击“添加视图”。对于这些愚蠢的问题,我深表歉意。但我不明白如何将每个ActionResult与其视图匹配?它将自动将操作名称与视图名称匹配视图名称和操作名称必须相同,否则您也可以返回视图(viewname);所以我创建了两个视图。一个用于索引,一个用于GetServiceData,两者的代码相同?
    [HttpPost]
    public ActionResult GetServiceData(JsonData model)
    {
        ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client();
        return View(obj.GetRuleDetail(model.Id));//Tihs will simply return view
    }