C# MVC-调用外部Web服务并在视图中显示它
我是asp.NETMVC新手。我手头的任务是联系web服务调用其方法之一,并在视图中显示它。我首先创建了一个新的MVC2应用程序。2010年。以下是我的index.aspx(默认页面)视图:C# MVC-调用外部Web服务并在视图中显示它,c#,asp.net-mvc,C#,Asp.net Mvc,我是asp.NETMVC新手。我手头的任务是联系web服务调用其方法之一,并在视图中显示它。我首先创建了一个新的MVC2应用程序。2010年。以下是我的index.aspx(默认页面)视图: 创建Soap请求 @使用(Ajax.BeginForm(“CreateSoapRequestResult”、“CreateSoapRequest”, 新的AjaxOptions{UpdateTargetId=“divSoapRequestDetails”}) { @Html.Label(“方法”) @
创建Soap请求
@使用(Ajax.BeginForm(“CreateSoapRequestResult”、“CreateSoapRequest”,
新的AjaxOptions{UpdateTargetId=“divSoapRequestDetails”})
{
@Html.Label(“方法”)
@Html.TextBox(“txtMethodName”)
@Html.Label(“用户名”)
@Html.TextBox(“txtUsername”)
@Html.Label(“密码”)
@文本框(“txtPassword”)
生成请求
}
但我在试图弄清楚如何传递数据方面束手无策。我假设我需要将其传递给控制器(或模型),然后控制器将创建soap请求,调用服务方法并获得响应。如果我错了,请纠正我。然后,我必须用另一种观点(最好)来表达它 你应该保持简单:
#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);
}
我实际上想在视图中传递表单中的数据。实际上,我并不像您通常那样使用服务引用调用web服务。我正在编写一个请求-响应代码来获取xml,并将其放入助手类中。我认为将表单中的数据输入控制器是第一步。然后使用我的助手类获取响应,填充模型并在视图中显示它。这不是正确的方法吗?这取决于,如果你在做MVC,那么你的模型应该在控制器中处理,而不是在表单中处理。对不起,我想我弄错了措辞。我的意思是将表单数据传输到控制器。就像一个登录表单。假设我想建立一个登录页面。如何获取控制器的用户名和密码?可能这是MVC 2.0,但我使用的ASP.NET MVC可以访问所有HttpContext及其包含的所有内容。
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.