I am trying to learn asp.net. I am making a demo website in which there would be an admin panel. The admin would update the Daily Messages which will get reflected in the main homepage. I am using MVC.
I have created the table in database as
create table DailyMsg(Sno int primary key, msg varchar(max));
This is my controller
public class DailyMsgsController : Controller
{
private amenEntities db = new amenEntities();
// GET: DailyMsgs
public ActionResult Index()
{
return Json(db.DailyMsgs.ToList(),JsonRequestBehavior.AllowGet);
}
}
On running the following URL, I am successfully able to see the data in JSON format.
https://localhost:44329/DailyMsgs
[{"Sno":1,"msg":"Hi!"}]
Now, I am stuck. I know that I would have to add another class for Data Access Layer, but I am confused as how should I parse this data and print it to the main HTML page.
From my research on the internet, I have found out that I might have to use JQuery. So, I wrote the following(with what I could understand from the internet as I am not familiar with JQuery) –
$.ajax({
url: "/DailyMsgs/Index",
type: "GET",
success: function (data) {
$("#div1").html(data);
}
});
This, of course, is not working and I can’t see anything on my webpage.
My Homepage.html
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
</body>
</html>
<script src="../Scripts/jquery-1.8.0.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
<link href="../Content/bootstrap.css" rel="stylesheet" />
<script src="../JQuery/DailyMsgsJQ.js"></script>
All I want is to read and parse msg
from JSON and display it on webpage.
Could you guide me as how should I proceed or is there any other way to achieve the purpose? Thanks a lot!
2
Answers
Your
<script>
tags are outside your<html>
tag. That means the scripts are probably not even executed, or not loaded in the correct order. You want jQuery and Bootstrap to be loaded first, so put them in the<head>
. Put your custom script just before the closing</body>
, so it is loaded last.Try this
If you still have error please get console.log(data); and send for me.