I have created a Html page say SomePage.Html and I want that Whenever I visit this page a method should be called.
Suppose I created a Controller DefautController and It has method named - Get() then whenever I visited the "../SomePage.Html" then this "Get()" should be raised.
SomePage.Html :-
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
</script>
</head>
<body onload="codeAddress();">
</body>
</html>
DefaultController :-
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
return View();
}
[System.Web.Http.HttpGet]
public IHttpActionResult Get()
{
}
}
How can I do that. I am very naive to this - WebApi/Asp.net thing. thanks :)
You could use jQuery
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$.ajax({
type: 'GET',
url: '/Default/index',
data: { },
cache: false,
success: function(result) {
alert(result);
}
});
</script>
You have to give method name Get instead of index method in URL
$.ajax({
url: '#Url.Action("Get", "Default")',
data: {},
type: 'GET',
datatype: "json",
contentType: 'application/json; charset=utf-8',
async: false,
success: function (data) {
alert(data.results);
}
});
Related
I was using signalR to manage database changes, when it happens I want to update the page to other users so that they see the change. But what I've done so far always loads, here is the code:
INDEX
#section scripts{
<script src="~/Scripts/jquery.signalR-2.4.3.min.js"></script>
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var hubNotify = $.connection.Connection4Hub;
$.connection.hub.start().done(function () {
getAll();
});
hubNotify.client.GetUpdateData = function () {
getAll();
};
});
function getAll() {
var model = $('#dataModel');
$.ajax({
url: '/Manage/GetUpdateData',
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html',
success: function(result) { model.empty().append(result); }
});
location.reload();
}
</script>
}
Connect4Hub
public class Connect4Hub : Hub
{
public static void BroadcastData()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<Connect4Hub>();
context.Clients.All.GetUpdateData();
}
}
MANAGE
public ActionResult GetUpdateData()
{
return PartialView("Index", db.Matches.ToList());
}
UPDATE
In the console while running i get this error
Uncaught Error: SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. .
start jQuery
https://localhost:44398/:216
jQuery 2
mightThrow
process
I am trying to post a data and trying to return from controller to back again and show it to alert box but dont know why this is not working
here is the controller code
[HttpPost]
public ActionResult getRequirmentsByProject(string projectname)
{
return Json(projectname, JsonRequestBehavior.AllowGet);
}
and here is my front end code
<input id="projName" type="text" name="Name" required="" value="javascript">
and this is my script code
var projectname = document.getElementById('projName').value;
$.ajax({
url: '/Worksheet/getRequirmentsByProject',
type: 'post',
data: { projectname },
contentType: 'application/json; charset=utf-8',
success: function (html) {
alert(html);
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
In your case, I am giving you a simple example on how you can POST your form variables to your controller using AJAX:
<script type="text/javascript">
var projectname = document.getElementById('projName').value;
var json = {
projectname: projectname
};
$.ajax({
url: '#Url.Action("getRequirmentsByProject", "Worksheet")',
type: 'post',
dataType: "json",
data: { "json": JSON.stringify(json)},
success: function (data) {
alert(data);
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
</script>
And in your controller, you can get this value as:
using System.Web.Script.Serialization;
[HttpPost]
public ActionResult getRequirmentsByProject(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
string projectname= jsondata["projectname"];
return Json(projectname);
}
its httpget and writing with a wrong way
[HttpGet]
public ActionResult getRequirmentsByProject(string projectname)
{
return Json(projectname, JsonRequestBehavior.AllowGet);
}
this is the right way thankyou for pointing out
My goal is:
I am trying to send values into a method of my controller to update the database (which is connected remotely via API).
I have checked several tutorials (How to pass parameters in $ajax POST? for example) but I can not send the data in my controller I have a 500 error that is due to my ajax call.
Could you tell me what to do?
View
$(document).ready(function () {
$.ajax({
url: "http://localhost:44338/Registration/ShowRegistration",
type: 'POST',
data: JSON.stringify({ "id": 1 }),
contentType: 'application/JSON',
success: function (data) { },
error: function () { }
})
});
Controller
[Authorize]
[HttpPost]
public async Task<ActionResult> ShowRegistration(Models.RegisterForm rF)
{
try
{
var test = rF.id;
Ok("success");
}
catch (Exception e)
{
Console.Write(e.Message);
return BadRequest();
}
return View();
}
Model
public class RegisterForm
{
public string id { get; set; }
}
Create Model first now(Standard Way)
Try this and let me know.
public class InfoModel
{
public string id { get; set; }
//Add your model fields here
}
Your Api
[HttpPost]
public async Task<ActionResult> ShowRegistration(InfoModel im)
{
//code
}
Your ajax call test this and then send more data:
$.ajax({
url: "url",
type: 'POST',
data: JSON.stringify({"id": id}),
contentType: 'application/JSON',
success: function (data) { },
error: function () {};
})
Tested Example:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: "http://localhost:62211/Home/ShowRegistration",
type: 'POST',
data: JSON.stringify({ "id": 1 }),
contentType: 'application/JSON',
success: function (data) { },
error: function () { }
})
});
</script>
</head>
<body>
</body>
</html>
Api
using System.Threading.Tasks;
using System.Web.Mvc;
namespace WebApplication5.Controllers
{
public class HomeController : Controller
{
[HttpPost]
public async Task<ActionResult> ShowRegistration(Models.info inf)
{
// Access inf.id
return null;
}
}
}
Why TestData does not receive anything?
POST http://localhost:46628/Home/TestData 500 (Internal Server Error)
index.cshtml:
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="~/Scripts/knockout-2.2.0.js"></script>
<button data-bind="click: sendata">send data</button>
<script>
function MyViewModel() {
var self = this;
self.sendata = function () {
$.ajax({
type: 'POST',
url: 'Home/TestData',
contentType: 'application/json; charset=utf-8',
data: { json: 'json', date: 'date' },
dataType: 'json'
});
}
}
ko.applyBindings(new MyViewModel());
</script>
Controller:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
public void TestData(string json,string date)
{
Console.WriteLine(json);
}
}
You use parameter data like this:
data: { json: 'json', date: 'date' },
Even though you specified that your content type is json, jQuery uses $.param to serialize your data, so instead of sending the json the data is sent like this:
json=json&date=date
Your server though expects json to be provided, so model binding fails.
Instead you should manually serialize the data to json before making AJAX call:
data: JSON.stringify({ json: 'json', date: 'date' }),
The rest of the code seems to be fine.
I have trying sending Ajax request to server in my web application, but it always return me 500 internal server error
following is my code
test.aspx
<script src="assets/plugins/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var postdata = JSON.stringify(
{
"Name": "rakeev",
"Age": "28"
});;
function testjson() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "test.aspx/GetId",
data: "{json: '" + postdata + "'}",
dataType: "json",
success: function (result) { alert("c"); },
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="button" value="text" onclick="testjson()" / >
</form>
</body>
test.aspx.cs
namespace testApp
{
public partial class test : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static Int64 GetId(string data)
{
using (JoyRydeAnalysis.Data.joyryde_analyzerEntities context = new JoyRydeAnalysis.Data.joyryde_analyzerEntities())
{
var id = context.tbl_item_list.Where(x => x.TXT_ITEM_NAME == data).Select(x => x.LNG_ITEM_ID).FirstOrDefault();
return id;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
Is there any other method used to send AJAX call in Asp.net webApplication ?