I have problem with saving new record to the database, using C# controller.
Here is the JS code:
<script type="text/javascript">
function save1(input1, input2) {
var lol = document.getElementById('input1').value + " " + document.getElementById('input2').value;
alert(lol);
$.ajax({
url: ' #Url.Action("Saving", "LanguagesController")',
type: "POST",
data: { name: input1, level: input2 },
dataType: "text",
success: function (result) {
alert("Yess!!")
},
error: function (request, error) {
alert("Noooo : " + error);
}
});
alert("End of function");
}
Here is my C# controller:
[HttpPost]
public ActionResult Saving(string name, string level)
{
Language lan = new Language();
lan.name_of_language = name;
lan.level_of_difficality = level;
db.Languages.Add(lan);
db.SaveChanges();
return View(db.Languages.ToList());
}
Thank you in advance
I can't see anything wrong with what you have (but are you really expecting text back?), but this would be better:
HTML:
<a class="btn" data-url="#Url.Action("Saving","LanguagesController")">Save</a>
Javascript:
$('a[data-url]').on('click',function() {
var url=$(this).data('url');
var input1=$('something').val();
var input2=$('somethingelse').val();
save1(url,input1,input2);
});
function save1(url, input1, input2) {
var lol = document.getElementById('input1').value + " " + document.getElementById('input2').value;
alert(lol);
$.ajax({
url: url,
type: "POST",
data: { name_of_language: input1, level_of_difficality: input2 },
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function(result) {
alert("Yess!!")
}).fail(function(jqXHR, textStatus, errorThrown) {
alert("Noooo : " + textStatus + " " + errorThrown);
});
alert("End of function");
}
C#:
[HttpPost]
public JsonResult Saving(Language lan)
{
db.Languages.Add(lan);
db.SaveChanges();
return Json(db.Languages.ToList());
}
PS. difficality is not spelled correctly.
Your problem is you're passing a control rather than a value
function save1(input1, input2) {
var lol = document.getElementById('input1').value + " " + document.getElementById('input2').value;
alert(lol);
$.ajax({
url: ' #Url.Action("Saving", "LanguagesController")',
type: "POST",
data: { name: getElementById('input1').value , level: getElementById('input2').value }, //changed from control to value
contentType: "application/json; charset=utf-8", // define contenttype
dataType: "json", //and the type you're expecting
success: function (result) {
alert("Yess!!")
},
error: function (request, error) {
alert("Noooo : " + error);
}
});
alert("End of function");
}
And at server side, you must get your model as input:
[HttpPost]
public ActionResult Saving(Language lan)
{
db.Languages.Add(lan);
db.SaveChanges();
return db.Languages.ToList();
}
Related
How to get All the elements of the Listbox when Button Click event is fired by using ajax call
I am using a function and trying to call the function in ajax call my function is working fine it returning all the elements from the List box when I am trying to bind it with the ajax call its not working i need to call the elements in the code behind:
function responseData2() {
debugger;
var oListbox = $("#submitlistbox2").each(function () {
var data = $(this).text() + " " + $(this).val()+"\n";
alert("The Names are: " + data);
});
var jobsheet = data;
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: "{ 'selectedJobSheet': '" + jobsheet + "'}",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
My code-behind data:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object Details4(string selectedJobSheet)
{
try
{
string constr = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("select customer_id,first_name from jobsheetDetails", con))
{
string _data = "";
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
_data = JsonConvert.SerializeObject(ds.Tables[0]);
}
return _data;
}
}
}
catch (Exception)
{
throw;
}
}
It seems your variable data was inside the loop. Try to use object method to fix your problem.
function responseData2() {
debugger;
var holder_all_data = [];
var oListbox = $("#submitlistbox2").each(function () {
var data = $(this).text() + " " + $(this).val()+"\n";
alert("The Names are: " + data);
holder_all_data.push({
var_name_data : data,
});
});
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: "{ 'selectedJobSheet': '" + holder_all_data + "'}",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
And then next, if you want to get the individual name value which's thrown by AJAX, you should use foreach loop and it should look like this. :D
e.g
foreach( selectedJobSheet as $item ){
var name = $item['var_name_data']; //include the object variable name
console.log(name);
}
Try this:
function responseData2() {
debugger;
var jobsheet = [];
$("#submitlistbox2").each(function () {
var data = $(this).text() + " " + $(this).val();
jobsheet.push(data);
alert("The Names are: " + data);
});
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: { "selectedJobSheet": JSON.stringify(jobsheet) },
dataType: "json",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
Code Behind:
[WebMethod]
public void Details4(string selectedJobSheet)
{
List<string> selectedJobSheetList = new List<string>();
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
dynamic data = serializer.Deserialize(selectedJobSheet, typeof(object));
foreach (var item in data)
{
selectedJobSheetList.Add(item);
}
}
It seems your data variable is overwritten in a loop and that is the issue. Hope below will help you.
function responseData2() {
var data = [];
var oListbox = $("#submitlistbox2").each(function (i) {
var data[i] = $(this).text() + " " + $(this).val()+"\n";
alert("The Names are: " + data[i]);
});
var jobsheet = JSON.stringify(data);
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: "{ 'selectedJobSheet': " + jobsheet + "}",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
Jquery code:
$('#sendmessage').click(function () {
var data1 = $('#message').val();
$.ajax({
type: "POST",
url: "NotificationTest.aspx/OnSubmit",
data:'{name:'+data1+'}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " +
textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
// alert("We returned: " + result);
$("#noti_Button").val(result); *** here can not catch value***
}
});
});
C# code:
here is my c# code to getting value from jquery and return again.
string is not returned or other thing i ca not underatand.
[WebMethod]
public static string OnSubmit(string name)
{
return name;
}
ERRor:Internal server error.
Make your method static:
[WebMethod]
public static string OnSubmit(string name)
{
return name;
}
I'm trying to pass data to controller for further processing but I get null in controller, however debug of js (ajax) shows the number anyway. What might be the problem?
Ajax:
$('.toggler_btn').on('click', function (event)
{
var id = $(this).attr('data-id');
if ($(this).text() === '+') {
$.ajax({
url: "/List/GetSubItems",
type: "POST",
contentType: "html",
dataType: "text",
data: '{"id":"' + id + '"}', // here it show the data, like 5 or some other number
success: function (data)
{
$('.element_wrapper [data-id="' + id + '"]').html(data);
}
})
$(this).html('-');
}
else $(this).html('+');
});
Controller:
[HttpPost]
public ActionResult GetSubItems(string id) // here I get null
{
int pID = 0;
int.TryParse(id, out pID);
List<H_Table> list = new List<H_Table>();
foreach (var item in db_connection.H_Table.Where(i => i.PARENT_ID == pID))
{
list.Add(item);
}
return PartialView(list);
}
$('.toggler_btn').on('click', function (event) {
var id = $(this).attr('data-id');
if ($(this).text() === '+') {
$.ajax({
url: '/List/GetSubItems',
type: 'POST',
dataType: 'json',
data: '{"id":"' + id + '"}',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('.element_wrapper [data-id="' + id + '"]').html(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("responseText=" + XMLHttpRequest.responseText + "\n textStatus=" + textStatus + "\n errorThrown=" + errorThrown);
}
});
$(this).html('-');
}
else $(this).html('+');
});
Use this one just copy and paste
Change your content type to "text" and change the data as well.
Change data type to "application/json" and data to this :
data :{
id : id
}
Your AJAX request has set contentType: "html" but you are actually sending JSON (with data: '{"id":"' + id + '"}'). And your controller is receiving a string.
So either change your AJAX call to send a raw string:
contentType: "text",
data: { id: id }
...or update your controller to receive JSON. This latter can be achieved by creating something like this:
public ActionResult GetSubItems(ViewModel model)
public class ViewModel {
public string Id { get; set; }
}
EDIT: also, for reference, you might want to see the difference between contentType and dataType.
I'm trying to pass some specific data to C# code-behind using AJAX code, but couldn't managed to accomplish it. I've tried using plain text data type and json format, but neither of them are working for me.
The following error occurred when I tried to send the data using json method:
Internal Server Error
when using text method, there is no error appear and the code comes through the success function, but the actually the data is never sent to the method of the code-behind class
And this is the ajax code using json format:
function searchClicked(sCriterion) {
$.ajax({
type: "POST",
url: "TokenRegistration.aspx/GetSearchCritetrion",
data: "{creiterion : " + sCriterion + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
});
}
And this is the ajax code using the text format:
function searchClicked(sCriterion) {
$.ajax({
type: "POST",
url: "TokenRegistration.aspx/GetSearchCritetrion",
data: sCriterion,
contentType: "application/text; charset=utf-8",
dataType: "text",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
});
}
Also here is the my code-behind method that the data should be sent to:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetSearchCritetrion(object selectedItem)
{
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(selectedItem.ToString());
}
I've used the exact same ajax code in another project and it works perfectly, but here i'm not getting where the error is, so any suggestions please?
Replace your code like this
.aspx
<script>
$(function () {
function searchClicked(sCriterion) {
$.ajax({
type: "POST",
url: "Default.aspx/GetSearchCritetrion",
data: "{creiterion : " + sCriterion + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
});
}
searchClicked("1");
});
</script>
and .cs file
[WebMethod]
public static String GetSearchCritetrion(String creiterion)
{
return "ok";
}
and App_Start
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Off;//Its may cause the error
routes.EnableFriendlyUrls(settings);
}
}
in your client side:
function searchClicked(sCriterion) {
//display the parameter
console.log(sCriterion);
if(sCriterion != "" || sCriterion != null)
{
var param= {
"selectedItem" : sCriterion
};
$.ajax({
type: "POST",
url: "TokenRegistration.aspx/GetSearchCritetrion",
data: param,
success: function(result) {
alert("We returned: " + result);
},
error: function(error){
console.log(error);
}
});
}
else
{
alert("No values!!");
}
}
server side:
[WebMethod]
public void GetSearchCritetrion(string selectedItem)
{
//add a breakpoint here....
}
I'm trying to use this rating plugin but I was unable to set the new score on click.
I'm making an ajax request on click event and get new calculated score. I wanted to set the new score inside the click event. What is the right way to do it?
<div class="rating" data-id="some-int" data-score="0.5"></div>
Javascript:
$(".rating").raty({
score: function () { return $(this).attr("data-score"); },
click: function (score, evt) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "./ajax.asmx/RateImage",
data: "{ ImgId: " + $(this).attr("data-id") + ", Score: " + score + "}",
dataType: "json",
async: false,
success: function (result) { actionResult = result.d; }
});
if (actionResult.Success) {
console.log("Score: " + actionResult.Message);
score = actionResult.Message;
} else { // cancel rating
alert(actionResult.Message);
return false;
}
}
});
There is a built in method to set new score, so just use:
$('.rating').each(function(i) {
var thisRating = $(this);
thisRating.raty({
score: function () {
return $(this).data('score');
},
click: function (score, evt) {
$.ajax({
type: 'post',
contentType: 'application/json; charset=utf-8',
url: './ajax.asmx/RateImage',
data: {
ImgId: thisRating.data('id'),
Score: score
},
dataType: "json",
success: function (result) {
thisRating.raty('score', result.d.Message);
}
});
return false;
}
});
});
Under docs - Functions you will find:
$('#star').raty('score');
Get the current score. If there is no score then undefined will be
returned.
$('#star').raty('score', number);
Set a score.
You can do
$(".rating").raty('setScore', score);
See it working
http://codepen.io/anon/pen/qdVQyO
According to the documentation, you can simply do $('#selector').raty({score: 3}) to set the score. So in the callback, you can call $(".rating").raty({score: actionResult.Message}) like so:
$(".rating").raty({
score: function () { return $(this).attr("data-score"); },
click: function (score, evt) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "./ajax.asmx/RateImage",
data: "{ ImgId: " + $(this).attr("data-id") + ", Score: " + score + "}",
dataType: "json",
async: false,
success: function (result) { actionResult = result.d; }
});
if (actionResult.Success) {
console.log("Score: " + actionResult.Message);
$(".rating").raty({score: actionResult.Message});
} else { // cancel rating
alert(actionResult.Message);
return false;
}
}
});