【问题标题】:asp.net mvc correctly get json data but can not show on the view pageasp.net mvc 正确获取 json 数据但无法在视图页面上显示
【发布时间】: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


    【解决方案1】:

    类似:

    $.getJSON("@Url.Action("GetJson","Technology"), null, function(data) {
    

    编辑 2-

    如果没有 Razor,它看起来像这样:

    $.getJSON("<%= Url.Action("GetJson","Technology") %>, null, function(data) {
    

    编辑-

    等待您要调用 Index AND GetJson 吗?这应该已经发生了,只需加载调用索引控制器操作的 /index 页面,然后在渲染的脚本中从那里调用 GJson 操作。为什么你认为你需要再次调用 Index?

    我想你的方法没有受到打击,因为 url 不正确。抓住 fiddler*,看看实际的 http 流量,看看它是否是 404 请求。

    *(一旦 fiddler 运行,将您的 url 更改为 http://localhost:port/..... 到 http://localhost.:port/.....)

    【讨论】:

    • 是这样的:我在主页上写了类似的方法,使用默认路由表,如果我调用:“localhost:port”,它会到达我的主页,如果我调用,数据可以正常工作“localhost:port/Home/Index”,然后一切都很好,除了没有数据显示,javascript中的getJSON()甚至没有被触发,你能告诉我为什么会这样吗?
    • 另外,当我加载 localhost:port/Technology/Index 时,没有 404 错误,它打开我的 index.aspx 页面,一切看起来都很好,只是没有数据。我也试过"@Url.Action("GetJson","Technology"),好像不行。谢谢
    【解决方案2】:

    我猜你可以修改“index”方法以便从“GetJSon”方法中获取数据,如下所示。

     public ActionResult Index() 
     {  
         return View("GetJson"); 
     }
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-08
      • 1970-01-01
      • 2017-02-27
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多