【发布时间】:2015-07-07 00:00:51
【问题描述】:
我对 MVC 框架很陌生。 目前我正在为来自谷歌的请求 REST API 构建一个应用程序并返回 JSON 对象(非常简单)。 我想从视图页面将两个参数传递给控制器。将html表单的两个参数传递给控制器的正确方法是什么?
我的目标是发送一个 REST 请求,然后从 JSON 对象中获取 JSON 对象和打印属性。 任何帮助将不胜感激。
controllers/homeController.cs 中的控制器
public class HomeController : Controller
{
public ActionResult Index()
{
string MyString = ViewBag.Message = "REST API Application";
return View();
}
[HttpPost]
public ActionResult SendRestRequest(Latitude latitude, Longitude longitude)
{
var stopwatch = new System.Diagnostics.Stopwatch();
var timestamp = new System.Runtime.Extensions();
// fetch data (as JSON string)
var url = new Uri("https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810,-119.6822510×tamp=1331161200&key=ggkiki9009FF");
var client = new System.Net.WebClient();
var json = client.DownloadString(url);
// deserialize JSON into objects
var serializer = new JavaScriptSerializer();
var data = serializer.Deserialize<JSONOBJECT.Data>(json);
// use the objects
decimal DstOffset = data.dstOffset;
decimal RawOffset = data.rawOffset;
ViewBag.jsonDstOffset = data.dstOffset;
ViewBag.jsonRawOffset = data.rawOffset;
ViewBag.jsonStatus = data.status;
ViewBag.jsonTimeZoneId = data.timeZoneId;
ViewBag.jsonTimeZoneName = data.timeZoneName;
return View();
}
}
namespace JSONOBJECT
{
public class Data
{
public decimal dstOffset { get; set; }
public decimal rawOffset { get; set; }
public string status { get; set; }
public string timeZoneId { get; set; }
public string timeZoneName { get; set; }
}
}
}
主页/查看 Index.htmlcs 页面
<form action="@Url.Action("SendRestRequest", "Home")" method="post" target="_blank">
Latitude:<br>
<input type="text" name="Latitude" value=""><br>
Longitude:<br><br>
<input type="text" name="Longitude" value=""><br><br>
<input type="submit" value="Send REST Requst">
</form>
【问题讨论】:
标签: c# json asp.net-mvc