Error while binding through ajax call - c#

I am doing ajax call in Asp.Net MVC with this code
$.ajax({
type: "GET",
url: '#Url.Action("GetAllFacts", "Home")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
//$('#AllFacts_Data').append("<div class='col-md-4'><div class='text-center facts-data-box bg_facts_grey'><div class='inner-div'><span><img src=" + data[0].ImageUrl + " class='image_top '></span><div class='text-center twit-all-content facts-content_blu'>'" + data[0].Content + "'</div></div></div></div>");
//$('#AllFacts_Data').append("<div class='col-md-4'><div class='text-center facts-data-box bg_facts_grey'><div class='inner-div'><span><img src=" + data[1].ImageUrl + " class='image_top '></span><div class='text-center twit-all-content facts-content_blu'>'" + data[1].Content + "'</div></div></div></div>");
},
error: function () {
alert("Error");
}
});
This hits to my Get Method GetAllFacts() with following codes
[HttpGet]
public JsonResult GetAllFacts()
{
try
{
using (var context = new DbDemo())
{
var allData_Facts = context.Objblog.Take(2).ToList();
return Json(allData_Facts, JsonRequestBehavior.AllowGet);
}
}
catch (Exception)
{
}
return Json("false", JsonRequestBehavior.AllowGet);
}
This is my code which returns list with 2 data properly, but after that it is not going to success method it alerts error as per Ajax error function.
Where I am wrong?

Try by
Remove assembly reference System.Web.Mvc out of your project.
Use nuget to install System.Web.Mvc for you project.
Verify Web.config to make sure it have System.Web.Mvc assembly.
Run to check.
Good luck!

ajax:
$.ajax({
type: "GET",
url: '/Home/GetAllFacts',
dataType: "json",
success: function (data) {
if (data.success) {
// connect to server successful and everything's ok
// access to server returned data: data.alldata
} else {
// connect to server successful but something went wrong
alert(data.ex); // throw exception message
}
},
error: function () {
// connect to server failure
}
});
controller:
[HttpGet]
public ActionResult GetAllFacts()
{
try
{
using (var context = new DbDemo())
{
var allData_Facts = context.Objblog.Take(2).ToList();
return Json(new { success = true, alldata = allData_Facts }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception e)
{
return Json(new { success = false, ex = e.Message }, JsonRequestBehavior.AllowGet);
}
}

Related

Parameter in my C# controller read as null from the AJAX call

I'm trying to take input from Users through a checkbox and store it in a table in my SQL DB, I've created all the link properly and my post AJAX call works well because I was able to receive information in my DB. The problem is the parameter received in my controller is receiving a null value which is storing a null value in my table, I know that my checkbox is pulling the right information because im printing it before hand but I feel like my AJAX setup may not be stringifying it properly.
$("#submitButton").click(function() {
var results = {};
$questions = $('#optionData');
for (i = 1; i < 6; i++) {
if ($questions.find('#option' + i).prop('checked')) {
results['option' + i] = $questions.find('#option' + i).val();
}
newResult = JSON.stringify(results)
};
console.log(newResult);
$.ajax({
url: "/Home/SaveData",
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: (newResult),
success: function(data) {
if (data == null) {
alert("Something went wrong");
}
},
failure: function(data) {
alert(data.dataText);
},
error: function(data) {
alert(data.dataText);
}
});
});
[HttpPost]
public ActionResult SaveData(string Options)
{
dataInsertion dataInsertion = new dataInsertion
{
// questionID = object.QuestionId,
options = Options,
// },
// companyID = object.companyID
};
try
{
if (ModelState.IsValid)
{
DB.dataInsertions.Add(dataInsertion);
DB.SaveChanges();
// RedirectToAction("Home");
}
}
catch (Exception e)
{
Console.WriteLine("error" + e);
}
return Json(new { sucess = "true" });
}

Internal Server Error when calling ajax post method

I'm facing problem with calling ajax POST method, it just returns error with message: Internal Server Error.
My script looks like this:
$('.add-column').click(function () {
var ids = [];
$('#table1 > tbody > tr.selected').each(function () {
var ident = $(this).attr('id');
ids.push(ident);
});
$.ajax({
url: '/Syzyf/AddUserColumns',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: { id : JSON.stringify(ids) },
cache: false,
success: function (result) {
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
And controller's method:
[HttpPost]
public ActionResult AddUserColumns(List<int> ids)
{
var userId = GetUserId(User.Identity.Name);
using (var ctx = new SyzyfContext())
{
foreach (var id in ids)
{
var uc = new UserColumns();
uc.ColumnId = id;
uc.UserId = userId;
ctx.UserColumns.Add(uc);
}
ctx.SaveChanges();
}
return Json("Success");
}
I thought that it may be problem with data, but when I've changed method to call ajax function foreach id in ids, It returned same error. What do I do wrong ?
EDIT
I've found solution.
The problem was with Database Table, it did not have PRIMARY KEY...

Transforming List into a Json C#

I'm trying to convert a List into a Json to send it to an Ajax Request, but when I recover only one register from the Database it works, but if I have more then one, the ajax returns an error.
Below is my code:
public ActionResult RecuperaLocalidadesPorUsuario(int usuarioId)
{
BpUsuario m = new BpUsuario();
IList<Localidade> states = m.ObterPorId(usuarioId).Localidades.ToList();
states.Add(m.ObterPorId(usuarioId).UsuaAreaPadrao);
var result = (from s in states.Where(x => x != null).Distinct().ToList()
select new { id = s.LocaCodigo, name = s.LocaNome}
).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
Here is the Ajax call
$.ajax({
cache: false,
type: "GET",
url: "#(Url.Action("RecuperaLocalidadesPorUsuario", "Usuario"))",
data: { "usuarioId": selectedItem },
contentType: 'json',
success: function (data) {
alert("entrou no success");
if (data.length == 0) {
ddlLocalidades.find('option').remove();
ddlLocalidades.append($('<option></option>').val("").html("O Usuário não tem localidades cadastradas"));
ddlLocalidades.attr("disabled", true);
} else {
ddlLocalidades.attr("disabled", false);
ddlLocalidades.find('option').remove();
ddlLocalidades.append($('<option></option>').val("").html("Todas"));
$.each(data, function (id, option) {
if (option.id == '#Request.Cookies.Get("UserAreaPadrao").Value') {
ddlLocalidades.append($('<option selected></option>').val(option.name).html(option.name));
} else {
ddlLocalidades.append($('<option></option>').val(option.name).html(option.name));
}
});
}
$('#ddlLocalidades').multiselect('rebuild');
},
error: function (data) {
alert("entrou no error");
}
});
I tried many links here at stackoverflow , but without any success, and I'm really stuck into this problem.

Issue with TypeScript and controller

So I'm converting a site form VB to C# and using TypeScript in the process. I have it successfully passing the data to the controller, however the controller post back to the same page instead to the next page.
Here's the TypeScript (full module here)
function formSubmission(submitId, submitUrl, formData, validation) {
if (!submitId || hasSubmit)
return false;
if (validation) {
if (!$("#empApp form").validate().form())
return false;
hasSubmit = true;
}
hasSubmit = true;
// add load status functionality
$(".modal").modal("show");
$.ajax({
type: "POST",
url: submitUrl,
data: formData,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (response) {
window.location.href = "/employment/application/references";
},
error: function (xhr, ajaxOptions, error) {
$(".modal-body").html("<h3>" + status + "<small>" + error + "</small></h3>");
setTimeout(function () {
$(".modal").modal("hide");
}, 100);
window.location.href = "/employment/application/work-experience";
}
});
}
Here's the Controller (full here)
[HttpPost, Route("Work-Experience")]
public ActionResult WorkExperience(List<EmploymentApplicationWorkExperience> appExperience)
{
EmploymentApplication empAppSession = getApplication();
if (!HasSession()) { return InvalidAppSession(); };
SetupViewBag();
if (!empAppSession.Steps.HasFlag(EmploymentApplication.ApplicationStepTypes.EducationSkills))
{
return PartialView(GetApplicationStepError());
}
if (ModelState.IsValid)
{
if (appExperience != null)
{
empAppSession.ApplicationWorkEperiences = appExperience;
// empAppSession.Application.empApWorkExperiences = (ICollection<empApWorkExperience>)appExperience;
empAppSession.StepCompleted(EmploymentApplication.ApplicationStepTypes.Workexperiences);
updateApplicationStep(empAppSession.Steps);
updateApplicationWorkExpriences(empAppSession.ApplicationWorkEperiences);
updateApplication(empAppSession.Application);
return RedirectToAction("References");
}
return PartialView(GetApplicationView("WorkExperience"), empAppSession.ApplicationWorkEperiences);
}
else
{
return PartialView(GetApplicationView("WorkExperience"), empAppSession.ApplicationWorkEperiences);
}
}
Used a unnecessary filter on Controller that if not valid, would continue to return the current page. Once removed, page continued with out post back issue.

alert ajax post method response from asp.net controller method in ajax success or in done function

I need to pass json response from controller method in case record created successfully and want to alert this message in ajax in success function or in done but I failing to achieve this for some reason.
javascript
$('#NewFunctionNavigationForm').submit(function (e) {
e.preventDefault();
var DataToPost = JSON.stringify($('#NewFunctionNavigationForm').serializeObject());
var formURL = $(this).attr("action");
$.ajax({
type: "POST",
url: formURL,
dataType: "JSON",
contentType: "application/json; charset=utf-8",
data: DataToPost,
})
.done(function (data, textStatus, jqXHR) { alert("Success: " + response); })
.fail(function (jqXHR, textStatus, errorThrown) { alert("Error"); })
.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) { alert("complete"); });
});
controller method
#region CreateNewFunctionNavigation
[HttpGet]
public ActionResult CreateNewFunctionNavigation()
{
return PartialView("CreateNewNavigation_Partial");
}
#endregion
[HttpPost]
public ActionResult CreateNewFunctionNavigation(CreateFunctionNavigation_SP_Map model )
{
if(ModelState.IsValid)
{
try
{
_FN_Services_a2.CreateFunctionNavigation(model);
return Json(new { Response = "Success" });
}
catch (DataException ex)
{
ModelState.AddModelError("", "Unable To Create New Function Navigation" + ex);
}
}
return PartialView("CreateNewNavigation_Partial", model);
//return Json(new { Url = Url.Action("CreateNewNavigation_Partial", model) });
} //end
Correcting your done function should work. Try below code:
.done(function (data, textStatus, jqXHR) { alert("Success: " + data.Response ); })
Let me know if you face any problem.

Categories

Resources