开发者

asp.net mvc correctly get json data but can not show on the view page

I am beginner for .net MVC. I guess my problem is related to route setting.

What I want to do is :I get data from database, in controller transfer data to json format and pass to view, use javascript decode json data and show on the html.

When I write methods under TechnologyController, type localhost:portnumber/Technology/Index, no decoded json data in html format, but if I type localhost:portnumber/Technology/GetJson It show me a page with pure json data (which means if I call GetJson() method separately, it works)

I write the same code in HomeController, it runs correct, all the route setting is default: routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults );

//This is my controller

public class TechnologyController : Controller
{
public ActionResult Index()
{

return View();
}

public JsonResult GetJson() 
{

Technology myTech = new Technolo开发者_运维知识库gy(); //get data from database (Tested correct) 
return Json(myTech.select(), JsonRequestBehavior.AllowGet);

}
}

//This is 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. 
.......
}
)};
)};

I understand if I call "localhost:portnumber/Technology/Index", it only execute index method, that is why GetJson method is not called, but what url should I call in order to call index() as well as GetJson.


something like:

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

edit 2-

Without Razor it would look like this:

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

Edit-

Wait you want to call Index AND GetJson? That should already be happening, just load the /index page which calls index controller action, then in the rendered script from there your invoking the GJson action. Why would you think you need to call Index again?

I imagine your method isnt getting hit because the url is incorrect. Grab fiddler*, and take a look at the acutal http traffic and see if it is 404'ing on the request.

*(once fiddler is running change your url to http://localhost:port/..... to http://localhost.:port/.....)


I guess you could modify the "index" method inorder to get the data from "GetJSon" method something like below.

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

Hope this helps!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜