How to binding model with ajax correctly - c#

I have question about passing values with ajax. I have done something like this:
$('#zlozZamowienie').click(function () {
var wycieczki = [];
$("input[name=Id_wycieczki]:checked").each(function () {
var id = $(this).attr('id');
wycieczki.push(id);
});
var productModel = {
Id_oferty: $("#Id_oferty").val(),
Nazwa_oferty: $("#Nazwa_oferty").val(),
Data_od: $("#Data_od").val(),
Data_do: $("#Data_do").val(),
Cena_za_miejsce: $("#Cena_za_miejsce").val(),
iloscDni: $("#iloscDni").val(),
SelectedKwaterunek: $("input:radio[name=SelectedKwaterunek]:checked").val(),
IdWycieczek: wycieczki
};
$.ajax({
type: "POST",
url: '#Url.Action("Szczegoly", "Oferta")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'skomponowanaOferta': productModel}),
dataType: "json",
success: function () {
alert('Success');
},
error: function (xhr) {
alert(xhr.error);
}
});
return false;
});
Szczegoly controller
[HttpPost]
public ActionResult Szczegoly(SzczegolyOfertyViewModel skomponowanaOferta)
{
if (ModelState.IsValid) {
...
};
TempData["Szczegoly"] = szczegoly;
return RedirectToAction("ZlozZamowienie", "Zamowienia");
}
Zamowienia Controller
public ActionResult ZlozZamowienie()
{
var skomponowanaOferta = (SzczegolyOfertyViewModel) TempData["Szczegoly"];
SzczegolyOfertyViewModel podsumowanie = new SzczegolyOfertyViewModel();
if (SprawdzWycieczki(skomponowanaOferta.IdWycieczek))
{
...
};
return View(podsumowanie);
}
Which is passing data correctly but because of this return false statement my button do not redirect me anywhere. When I change this return to true or just delete it, this ajax pass nulls. What am I doing wrong?
EDIT: I have error from ajax like this:

Ok I found answer here
RedirectToAction not working after successful jquery ajax post?
and then I add this to my ajax:
location.href="url"
like as #vinayakj said

Related

Why does my ajax call not returning my data from controller?

I'm having a hard time getting the data from client but my code on visual studio when I'm on a breakpoint it gets the data but I cant receive it on my browser.
Here's my AJAX call
function GetRecord() {
var elemEmployee = 55;
var startDT = $('#searchFilterStartDate').val();
var endDT = $('#searchFilterEndDate').val();
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data);
}
});
}
here's my controller:
[HttpGet]
public List<DTRRecordList.Entity> GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
return entity.GetDTR(data);
}
As you can see below I got 38 records but I can't receive it on my js even that console.log('Data Success') is not shown on my console.
You need to return JSON from your Controller method. You can change your method to:
[HttpGet]
public JsonResult GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
var getDTR= entity.GetDTR(data);
return Json(new {dtrData= getDTR});
}
And in your Ajax call:
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data.dtrData);
},
error: function(error) {
console.log(error)
}
});
After a discussion with O.P and seeing the code, it was found that the issue was happening because the form submit was happening which was causing the page to reload twice. After removing the form event and adding the click event in:
$(document).ready(function () {
//On Clink "Search Button"
$("#searchbtn").click(
function () { GetRecord(); });
});
The data seems to be coming as expected.

No errors on backend, but Ajax function is failing

I have an Ajax Call and a Controller with some methods and there is something weird.
The Ajax call can reach the Controller Method. The method is returning the value perfectly, no errors, nothing. However, in the AJAX the return is coming with error (not on success of Ajax).
Moreover, If I inspect the return I can see the correct values on responseJson, but the status is 404 and statusText is "error" ({"readyState":4,"status":404,"statusText":"error"})
Anyone have an idea what is going on? There is no error in backend, however error in Ajax.
Controller Method
public JsonResult SceneListUpdated(string sceneId)
{
SceneListModel model = new SceneListModel();
var licenseValidationState = KeygenLicenseState.CheckLicense();
if (licenseValidationState == 0)
{
SceneListService sceneService = new SceneListService();
model = sceneService.GetSceneListUpdated(sceneId);
return Json(new { Success = true, data = model }, JsonRequestBehavior.AllowGet );
}
return Json(new { Success = false, data = "" }, JsonRequestBehavior.AllowGet);
}
Ajax Function
$.ajax({
url: "/api/test/SceneList/SceneListUpdated?sceneId=" + sceneIdAux, //Method in controller
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (e) {
},
error: function (data) {
}
});
try to fix the ajax
$.ajax({
url: "/api/test/SceneList/SceneListUpdated/"+ sceneIdAux, //Method in controller
type: "GET",
success: function (e) {
},
error: function (data) {
}
});
and maybe you can try one of these routing since you have 404
[Route("{sceneId}")]
[Route("~/api/SceneList/SceneListUpdated/{sceneId}")]
public JsonResult SceneListUpdated(string sceneId)

Trying to Get Data using Ajax call to Controller method MVC My code Attached

I am calling jquery function on dropdown value change jquery method is ,
function MyFunction() {
alert($('#DDlSurvey').val());
$.ajax({
url: "#Url.Action("GetSelectedQuestion", "ConductSurveyController")",
data: { prefix: $('#DDlSurvey').val() },
type: "GET",
dataType: "json",
success: function (data) {
// loadData(data);
alert(data)
alert("Success");
},
error: function () {
alert("Failed! Please try again.");
}
});
//$('#YourLabelId').val('ReplaceWithThisValue');
}
</script>
Function I'm calling and I am getting dropdown value alert
Now, Function that I am calling is "GetSelectedQuestion" in controller "ConductSurveyController"
Method is like ,
[HttpPost]
public JsonResult GetSelectedQuestion(int prefix)
{
List<SelectList> Questions=new List<SelectList>();
// Here "MyDatabaseEntities " is dbContext, which is created at time of model creation.
SurveyAppEntities ObjectSur = new SurveyAppEntities();
// Questions = ObjectSur.Surveys.Where(a => a.ID.Equals(prefix)).toToList();
I don't think this method is calling as I am getting error
"Failed! Please try again"
From my script.
Hopes for your suggestions
Thanks
var e = from q in ObjectSur.Questions
join b in ObjectSur.SurveyQuestions on q.ID equals b.QuestionID where b.SurveyID.Equals(prefix)
select q ;
return new JsonResult { Data = e, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
I think you are using controller name straight forward. your ajax code be something like this.
var PostData= { prefix: $('#DDlSurvey').val() }
var ajaxOptions = {
type: "GET",
url: '#Url.Action("GetSelectedQuestion", "ConductSurvey")',//Actionname, ControllerName
data: PostData,
dataType: "json",
success: function (result) {
console.log(result);
},
error: function (result) {
}
};
$.ajax(ajaxOptions);
Your method in your controller is decorated with HttpPost, while in your ajax you have specified the type of your request is get . You can either change your method to get like this:
[HttpGet]
public JsonResult GetSelectedQuestion(int prefix)
{
}
Or change your request type to post in your Ajax call:
$.ajax({
url: "#Url.Action("GetSelectedQuestion", "ConductSurveyController")",
data: { prefix: $('#DDlSurvey').val() },
type: "Post",
Also the Controller is redundant in ConductSurveyController, you need to remove it and simply call it as ConductSurvey:
url: '#Url.Action("GetSelectedQuestion", "ConductSurvey")',

Redirect with Ajax POST

i'm new with ajax and i'm trying to call a post action from an ajax method like that
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
window.location.replace('#Url.Content("~/DemandeLocation/MaSelectionOffre")');
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
my post method goes with success but instead of redirectin me to the MaSelection View it return the first view where i call the method, so i tried to put a "Success" fragment in my ajax method and i puted a location replace by "Ma selection" view but i know that the view lose the id so it become null, how can i do it with Ajax,
here my post action for more details
[HttpPost]
[Authorize(Roles = "Locataire")]
public ActionResult MaSelectionOffre(string id)
{
int DemandeLocationGetbyId = Convert.ToInt32(id);
var selectionOffre = db.SelectionOffreLocationSet.Where(model => model.DemandeLocationPublication_ID == DemandeLocationGetbyId).ToList();
return View("MaSelectionOffre", selectionOffre);
}
use json as datatype;
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
dataType:"json",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
window.location.href = msg.redirect;
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
also you need this ;
Convert object to JSON string in C#
If you want redirect page, after ajax call you should use
...
success: function (msg) {
window.location.href = '#Url.Action("MaSelectionOffre", "DemandeLocation")';
},
...
EDIT
If you want replace result, use something like following:
HTML
<div id="updateTargetId">
//table
//tr
//td
//your button that has cssClass buttonSelection
</div>
JS
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
dataType:"json",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
$("#updateTargetId").html(msg);
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
CONTROLLER (return PartialView)
[HttpPost]
[Authorize(Roles = "Locataire")]
public ActionResult MaSelectionOffre(string id)
{
int DemandeLocationGetbyId = Convert.ToInt32(id);
var selectionOffre = db.SelectionOffreLocationSet.Where(model => model.DemandeLocationPublication_ID == DemandeLocationGetbyId).ToList();
return PartialView("MaSelectionOffre", selectionOffre);
}
i changed my action to a get action and in my button i just added window.location.replace with link and ID
<button type="button" class="buttonSelection" onclick="window.location.replace('#Url.Content("~/DemandeLocation/MaSelectionOffre?id="+item.Publication_ID)')"> <span class="ui-icon ui-icon-cart"></span> </button>

Ajax POST not posting list

I am passing data to controller through Ajax call.
Following is the ajax code:
var month_List = [];
$('#dojMonths :selected').each(function (i, selectedItem) {
month_List[i] = $(selectedItem).text();
});
var from_Month = $("#fromKPAMonthPicker").val();
var from_Year = $("#fromKPAYearPicker").val();
var to_Month = $("#toKPAMonthPicker").val();
var to_Year = $("#toKPAYearPicker").val();
$.ajax({
url: '/Home/_DataByFromTo',
type: "POST",
data: {
doj_Month_List: month_List,
from_Month: from_Month,
from_Year: from_Year,
to_Month: to_Month,
to_Year: to_Year
},
dataType: "html",
success: function (data) {
$("#divList").html(data);
}
});
Controller action method:
[HttpPost]
public ActionResult _DataByFromTo(List<Int32> doj_Month_List, Int16 from_Month, Int16 from_Year, Int16 to_Month, Int16 to_Year)
{
return View();
}
It was working in my old code perfectly fine. I don't know whats the problem. because all data are passing perfectly except this array of jquery.
To disable deep serialization of objects you need to set traditional property to true.
$.ajax({
url: '/Home/_DataByFromTo',
type: "POST",
data: {
doj_Month_List: month_List,
from_Month: from_Month,
from_Year: from_Year,
to_Month: to_Month,
to_Year: to_Year
},
dataType: "html",
traditional: true,
success: function (data) {
$("#divList").html(data);
}
});
When set to true it results in a shallow serialization.
Following link might be of help.
https://api.jquery.com/jQuery.param/
try using push
var month_List = [];
$('#dojMonths :selected').each(function (i, selectedItem) {
month_List.push($(selectedItem).text());
});

Categories

Resources