【发布时间】:2011-11-21 09:17:14
【问题描述】:
我是 .net MVC 的初学者。我想我的问题与路线设置有关。
我想要做的是:我从数据库中获取数据,在控制器中将数据传输为 json 格式并传递给视图,使用 javascript 解码 json 数据并显示在 html 上。
当我在 TechnologyController 下编写方法时,键入 localhost:portnumber/Technology/Index,没有 html 格式的解码 json 数据,但是如果我键入 localhost:portnumber/Technology/GetJson 它向我展示了一个包含纯 json 数据的页面(这意味着如果我单独调用 GetJson() 方法,它就可以工作)
我在 HomeController 中编写了相同的代码,它运行正确,所有路由设置都是默认的: 路线.MapRoute( "Default", // 路由名称 "{controller}/{action}/{id}", // 带参数的 URL new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值 );
//这是我的控制器
public class TechnologyController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult GetJson()
{
Technology myTech = new Technology(); //get data from database (Tested correct)
return Json(myTech.select(), JsonRequestBehavior.AllowGet);
}
}
//这是Javascript:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("Technology/GetJson/", null, function(data) {
sss.innerHTML+=data["title"];// this part is correct (I already tested,please ignore), the purpose is to parse json data to html.
.......
}
)};
)};
我知道如果我调用“localhost:portnumber/Technology/Index”,它只执行 index 方法,这就是为什么不调用 GetJson 方法,但是我应该调用什么 url 才能调用 index() 以及 GetJson .
【问题讨论】:
标签: c# asp.net asp.net-mvc getjson