how to get value from document.getelementbyid in c sharp - javascript

I want to pass the element's value into a controller
JavaScript:
var element = document.getElementById("valueSelected");

Query String
Document.location="/ControllerName/ActionName/Value";
Ajax
$.Post('/ControllerName/ActionName/',{Parameter: element});

No problem
Script
function Delete() {
$.getJSON("/ControllerName/ActionName/", {Id : Value}, function (data)
{
alert(data)
})
};
C#
public JsonResult ActionName(int? id)
{
string Data = "Sample Data";
return Json(Data, JsonRequestBehavior.AllowGet);
}

Let suppose Home is your Controller.
Add a function in your controller who can handle your ajax request. Suppose function name is getValue:
public void GetValue(string elementValue)
{
//add your controller logic here
}
In your javascript, I use jquery to perform ajax request, you need to jquery to do this so:
var element = document.getElementById("valueSelected");
$.ajax({
type: "POST",
data : { elementValue : $(element).val() },
url: '#Url.Action("GetValue", "Home")'
}).done(function (data) {
console.log('done');
});

Related

Return parameter null in controller from ajax

I don't know what happened the value sent to the controller is always null, even though in the console.log the value is there, please I need help
this is my ajax:
$('#ddlItemName').change(function () {
var ItemCode = $('#ddlItemName').text();
if (ItemCode != '') {
var RequestParam = {
search: ItemCode
}
console.log(RequestParam);
$.ajax({
url: '/Order/CustomerItemOrders',
type: 'POST',
data: JSON.stringify(RequestParam),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data[0].Name);
},
error: function (data) {
toastr.error(data);
}
});
}
$('#ddlItemName').text('');
});
This is my controller :
[HttpPost]
public JsonResult CustomerItemOrders([FromBody] string search)
{
var result = _order.BindCustomerOrders(search);
return Json(result.data);
}
This is my error :
enter image description here
I've tried adding '[FromBody]' but the value parameter still doesn't get sent
I recomend you add the parameter to query
If you insist on pass the value with request body
Try creat a model:
public class SomeModel
{
public string search{get;set;}
}
in your controller:
public JsonResult CustomerItemOrders([FromBody] SomeModel somemodel)
{
.......
}

ASP.NET: Ajax doesn't send string

I have this method to send some data with ajax:
function SendData(foodID, basketID) {
var data = { FoodID: foodID, BasketID: basketID };
$.ajax({
url: '/Order/Post',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json;utf-8',
datatype: 'json'
}).done(function (data) {
console.log(data);
}).fail(function (data) {
console.log("Error: " + data);
});
}
In C#, my Post Method in my Order controller gets triggered, but the string I want to hand over is null:
public bool Post(string s)
{
//When this gets executed, s is null
return true;
}
I tested this by executing SendData(1,1) directly on a button click. What is the mistake I'm doing and how can I get the string in my Post-Method?
you are post the object. not string.
you can try generate to object and load this object. or add new one parameter to action (foodId and basketId but you must post like that if you check this option data:{foodId,basketId})
//model
public class SomeObject{
public string FoodId {get;set;}
public string BasketId {get;set;}
}
//code
public bool Post(SomeObject data)
{
return true;
}
It seems for me your data structure to the Post action doesn't match action parameter names. Try this:
[HttpPost]
public bool Post(string foodID, string baskedID)
{
return true;
}
I believe you have to name your data that's being passed like so:
data: { 's': JSON.stringify(data) }

Problem with jQuery post to ASP.NET Core controller

I have gone through this solution on stackoverflow but I couldn't solve my problem.
In HomeController I have a method named as Audit which I want to be posted from /Home/Index page's script through jQuery. The controller looks like:
public class HomeController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Audit([FromBody] JObject jObject)
{
if (jObject != null)
{
return Json("success");
}
return Json("failed");
}
}
In the /Home/Index pages's javascript file I have tried to post a JSON Object to that Audit in a way like this:
var auditData = {};
$(document).ready(function(){
var request = $.getJSON('http://www.geoplugin.net/json.gp', function (responseData, status) {
auditData = {
Latitude : responseData.geoplugin_latitude,
Longitude : responseData.geoplugin_longitude
};
$.post('Audit', auditData, function (response) {
console.log(response);
});
});
});
I want the auditData object to be posted as JObject in /Home/Audit but something is going wrong. I think there is problem either in controller or, in $.post method. How can I solve this problem?
Your post URL is wrong, and you need to name the data you're posting back as jObject as well to match what you defined in your controller.
$.post('#Url.Action("audit", "home", new { area = "" })', { jObject: auditData },
function (response) {
console.log(response);
});
There are multiple issues in your current code, check points below one by one:
As the suggestion from Rory, your request url is wrong, which should be Home/Audit
If you post request without antitoken, you should remove [ValidateAntiForgeryToken]
You should post request data with json instead of form data.
Code:
Client
#section Scripts{
<script type="text/javascript">
var auditData = {};
$(document).ready(function(){
auditData = {
Latitude : "l1",
Longitude : "l2"
};
$.ajax({
type: 'POST',
url: 'Home/Audit',
data: JSON.stringify(auditData),
success: function(data) { alert('data: ' + data); },
contentType: "application/json"
});
});
</script>
}
Server:
public class HomeController : Controller
{
[HttpPost]
//[ValidateAntiForgeryToken]
public JsonResult Audit([FromBody]JObject jObject)
{
if (jObject != null)
{
return Json("success");
}
return Json("failed");
}
}

How to pass a list from spring controller to ajax in jquery

This is my Jquery! Here i am not getting success response, instead a error response is thrown when a list is returned from controller to below jquery. Please let me know where i am going wrong.
//ajax method to retrieve the data from controller where controller returns list
function doAjaxPost() {
// get the form values
var pid = $('#pid').val();
$.ajax({
type: "GET",
url: "http://localhost:8085/HMS/iochart1.html",
data: "pid=" + pid,
success: function (response) {
alert(response.list4);
$.each(response, function (index, datec) {
alert(datec.name); //to print name of employee
});
},
// Even though controller returns the list,but i am not getting the above success response,instead below error method is executed.
error: function (e) {
alert('Error: ' + e);
}
});
}
Below is the controller which returns the list.
#RequestMapping(value="/iochart1", method = RequestMethod.GET)
public #ResponseBody List<Iochart> iochart1(#ModelAttribute("s") Iochart s) {
System.out.println("Patient"+s.getPid());
List<Iochart> list4 = dao.getPatientdet1(s.getPid());
return list4;
}
getPatientdet1() which retrieves the data from database
public List<Iochart> getPatientdet1(String pid) {
// TODO Auto-generated method stub
System.out.println(pid);
return template.query(
"select pid,name,fileno,age,gender,date,wardno,doctord,doctsig,ratef,nursesig,time,type,amount,typecommence,amtgiv,urine,vomitus,remarks from iochart where pid='"+pid+"'",
new RowMapper<Iochart>() {
public Iochart mapRow(ResultSet rs, int row) throws SQLException {
Iochart i = new Iochart();
i.setPid(rs.getString(1));
i.setName(rs.getString(2));
i.setFileno(rs.getString(3));
i.setAge(rs.getString(4));
i.setGender(rs.getString(5));
i.setAdmdate(rs.getString(6));
i.setWardno(rs.getString(7));
i.setDoctord(rs.getString(8));
i.setDoctsig(rs.getString(9));
i.setRatef(rs.getString(10));
i.setNursesig(rs.getString(11));
i.setTime(rs.getString(12));
i.setOraltype(rs.getString(13));
i.setOralamt(rs.getString(14));
i.setOralcommence(rs.getString(15));
i.setAmtgiv(rs.getString(16));
i.setUrine(rs.getString(17));
i.setVomitus(rs.getString(18));
i.setRemarks(rs.getString(19));
System.out.println(rs.getString(2));
return i;
}
}
);
}
Change your controller method like so. Mind the #RequestParam that is used to get the pid
#RequestMapping(value="/iochart1", method = RequestMethod.GET)
public #ResponseBody List<Iochart> iochart1(#RequestParam(name = "pid") String pid) {
return dao.getPatientdet1(pid);
}
And your ajax url like so
function doAjaxPost() {
// get the form values
var pid = $('#pid').val();
$.ajax({
type: "GET",
url: "http://localhost:8085/HMS/iochart1", //Don't postfix .hmtl
data: "pid=" + pid,
...
});
}

jQuery autocomplete for json data

I am returning array of strings from controller to ajax call. trying to set to textbox those values. in textbox it is not populating. but I can see data in success method.
[HttpGet]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult GetWorkNamesAutoPoplate(string companyName)
{
...
var newKeys = companyNameslst.Select(x => new string[] { x }).ToArray();
var json = JsonConvert.SerializeObject(newKeys);
return Json(json, JsonRequestBehavior.AllowGet);
}
JS
$(document).on('change', '[name="FindCompanyName"]', function () {
$('[name="FindCompanyName"]').autocomplete({
source: function (request, response) {
$.ajax({
url: "GetWorkNamesAutoPoplate",
type: "GET",
dataType: "json",
data: { companyName: $('[name="FindCompanyName"]').val() },
success: function (data) {
alert(JSON.stringify(data));
response($.map(data, function(item) {
console.log(item);
return {
value: item
}
}));
}
});
},
messages: {
noResults: "", results: ""
}
});
});
alert(JSON.stringify(data)); display like this.
How to populate this data in textbox
The return type of your json is an array of arrays, i think you should return it as an array
var newKeys = companyNameslst.ToArray();
also, your data are serialized twice,
one from line,
var json = JsonConvert.SerializeObject(newKeys);
and second time from JsonResult action filter
return Json(json, JsonRequestBehavior.AllowGet);
sending json data like,
return Json(newKeys, JsonRequestBehavior.AllowGet);
instead of
var json = JsonConvert.SerializeObject(newKeys);
return Json(json, JsonRequestBehavior.AllowGet);
should work.
hope this helps.
This may resolve your issue :
success: function (data) {
alert(JSON.stringify(data));
if (data != null) {
response(data.d);
}
}
Also this link might help you to get some information :How to use source: function()... and AJAX in JQuery UI autocomplete

Categories

Resources