Pass differents values in ajax - c#

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;
}
}
}

Related

SignalR notification reload always the pyhjyjage

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

how to fix this my following code is not working

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

Ajax call returning 500 error in Asp.Net Web application

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 ?

Invoking Controller method from Html page

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);
}
});

Retrieving data from Ajax POST in asp.net

I have an ajax POST like this
$(document).ready(function () {
var pcontent = document.body.innerHTML;
var url = new URI();
$.ajax({
url: url,
type: "POST",
data: { "pcontent": pcontent },
success: function (data) {
alert($(data).find(".right-panel").html());
},
complete: function () {
},
error: function (jqXHR, error, errorThrown) {
if (jqXHR.status) {
alert(jqXHR.responseText);
} else {
alert("Something went wrong");
}
}
});
return false;
});
I am little confused how i could retrieve data (pcontent) that i post here in my code behind.actually in a specific class file i need to implement this logic .
You have to create a controller action:
public class HomeController: {
// model
public class PDocument {
public string pcontent {get;set;}
}
[HttpPost]
public ActionResult SaveDocument(PDocument pcontent){
// do something
return new JsonResult() { Data = new { Success = true } };
}
}
JS:
$.ajax({
url: "Home/SaveDocument",
type: "POST",
data: { "pcontent": pcontent}
...});
Note:
You don't need to create a model on server if set
$.ajax({
url: "Home/SaveDocument",
type: "POST",
data: pcontent
});
// server side
public ActionResult SaveDocument(string pcontent){
// do some thing
}
For security reason, your html must be encoded before calling ajax
In case you new to mvc, then this is a good way to start: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-controller

Categories

Resources