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...
Related
I have this code(JQuery) in my View:
$("form").submit(function (e) {
e.preventDefault();
var form = this;
var link = '#Url.Action("Action", "Controller")';
var args = {
MyFVal: MyFVal.val(),
MySVal: MySVal.val()
};
$.ajax({
type: "GET",
url: link,
data: args,
dataType: "json",
success: function (data) {
alert(data.acces);
if (data.acces) {
AllEnable();
form.submit();
}
else {
alert(data.erromessage);
}
},
error: function () {
alert("Error. Kontaktujte správce.");
}
});
});
When I gets submitted then I have this if in my save action.
if (Request.Form.ContainsKey("Insert"))
{
// do code that is supposed to run
}
else if (Request.Form.ContainsKey("Edit"))
{
// do another code
}
My problem is that because I submitted form by JQuery this if and elseif never gets executed.
Thanks for any help!
You might want to pass value for your requirements in Action condition. See operationType sample parameter
var obj = {
UniqueId: modelUniqueId.val(),
Name: modelName.val(),
operationType: $("[name=operationType]").val()
};
$.ajax({
type: "POST",
url: '/hrms/Class/Index',
data: obj,
success: function (result) {
if (result.success == true) {
createAndProcessPageAlert("success", result.message);
}
else {
createAndProcessPageAlert("error", result.message);
}
And in your Controller \ Action
[HttpPost]
public JsonResult Index(string operationType, ClassModel model)
{
var result = new HttpResponseModel<ClassModel>();
var user = Request.GetUserProfile();
if (operationType == "add")
my project is an MVC Web application I am using ajax call to get a huge list of data as JSON.
Here is the code( i am not sure what I a missing ):
$.ajax({
url: url, //server
type: "POST",
async: true,
data: { id: id },
dataType: "json",
success: function (data) {
debugger;
jQuery.each(data, function (i, val) {
//Success code
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
window.baseShowModalOkCancel("<p>Backlog Data</p>", "<p>Error in Database</p>", "ERROR");
}
});
}
Action Controller:( This is a post method in return statement I can see the list of object with the data.
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetBacklogWithData(string id)
{
using (var db = new LiensTrackerEntities())
{
List<BackLogDataList> backLogData = new List<BackLogDataList>();
List<BackLogData> backLog;
backLog = db.BackLogDatas.OrderBy(x =>x.CaseNumber).ToList();
foreach (var item in backLog)
{
BackLogDataList backLogDataList = new BackLogDataList
{
FileNo = item.FileNo,
BackLogId = item.BackLogID,
FirstName = item.FirstName,
LastName = item.LastName,
Middle = item.Middle,
Suffix = item.Suffix,
Address = item.Address,
Address2 = item.Address2,
City = item.City,
St = item.ST,
Zip = item.SP1ZIP,
AmaesRecordCreatedDate = item.AMAESRecordCreatedDate != null ? item.AMAESRecordCreatedDate.ToString().Split(' ')[0] : null,
AddedInRecipient = item.AddedInRecipient
};
backLogData.Add(backLogDataList);
}
}
return Json(backLogData, JsonRequestBehavior.AllowGet);
}
}
It returns with 200 ok but execute the error function when i look into console i found the following error:
Thee error is due to max json string length. the solution is
MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer
i have a issue , my problem is it i can't use my object form my model using EF , i need this method for a autocomplete search;
this is my error message :
"The System.NotSupportedException exception occurred HResult = 0x80131515 Message = The entity type or complex type 'PizzaTn.Context.ViewModels' cannot be built in a LINQ to Entities query. Source = Procedure call tree:
public JsonResult GetSearchValue(string search)
{
PizzaTnContext db = new PizzaTnContext();
List<VilleModels> allsearch = new List<VilleModels>();
allsearch = db.Villes.Where(x => x.VilleName.Contains(search)).Select(x => new VilleModels
{
IdVille = x.IdVille,
VilleName = x.VilleName
}).ToList();
return new JsonResult { Data = allsearch, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
this my HTML
<script>
$("#searchInput").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetSearchValue", "Home")',
datatype: "json",
data: {
search: $("#searchInput").val()
},
success: function (data) {
response($.map(data, function (item) {
return { label: item.VilleName, value: item.VilleName };
}
)
);
},
error: function (xhr, status, error) {
alert("error");
}
});
}
});
</script>
the solution is to add an argumant .AsEnumerable() .. thanks George:
db.Villes.Where(x => x.VilleName.Contains(search)).AsEnumerable().Select(x => new VilleModels { IdVille = x.IdVille, VilleName = x.VilleName }).ToList();
when I call one webapi from ajax, if I return something different from simple string or int, the request is still pending.
here my javascript:
var endPoint = "/api/services/attivita/set";
$.ajax({
url: endPoint,
data: JSON.stringify(
{
'id': attivita.IDTipoAttivita,
'descrizione': $('#Descrizione').val()
}
),
dataType: 'json',
contentType: "application/json;charset=utf-8",
processData: false,
type: 'post',
success: function (data) {
console.log('ok');
},
error: function (data) {
console.log('ko');
}
});
and here webapi code
[System.Web.Http.HttpGet]
[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/services/attivita/set")]
public TipoAttivita SetAttivita([FromBody] dynamic obj)
{
var id = (int)obj.id;
var descrizione = obj.descrizione.ToString();
var nuovo = id == -1;
var attivita = new TipoAttivita()
//do stuff of attivita object
this.CurrentDb.TipoAttivita.Add(attivita);
this.CurrentDb.SaveChanges();
return (attivita);
}
If I change to "public int...." and "return(1);" at the end of the function everything works fine.
in WebApiConfig.cs I have this
var jsonFormatter = new JsonMediaTypeFormatter
{
SerializerSettings = {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}
};
jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
config.Formatters.Clear();
config.Formatters.Add(jsonFormatter);
Any idea?
Thanks a lot
Try to change return type to IHttpActionResult and return Ok(attivita)
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.