Spring ModelAndView not working with ajax call - ajax

Ajax calls a Spring Controller employee_edit but the ModelAndView is not working. It does not redirect to jsp page with object.I want to redirect to the page employee_registration.jsp with the object employee. Code has no error.
Ajax
$('#example1 tbody').on( 'click', 'button1', function () {
var eid = table.row( $(this).parents('tr') ).data().eid;
$.ajax({
type:"GET",
url:"employee_edit?eid="+eid
});
Controller
#RequestMapping(value="/employee_edit", method=RequestMethod.GET)
public ModelAndView RegitrationEdit(#RequestParam("eid") long eid)
{
Employee employee=employeeService.getEmployee(eid);
ModelAndView mv=new ModelAndView();
mv.setViewName("employee/employee_registration");
mv.addObject("employee",employee);
return mv;
}
After running the code it does not show any error. Going through the code ModelAndView("employee/employee_registration","employee",employee); but nothing happens.
Thanks in advance.

I think in your ajax call you need to add the success parameter. You can simply modify your call as
$.ajax({
type:"GET",
url:"employee_edit",
data:{"eid":eid},
success:function(data){
}
});
or you can also add only the success parameter in your code
$.ajax({
type:"GET",
url:"employee_edit?eid="+eid
success:function(data) { }
});
But I prefer the first one. Its more clear.
This should complete the ajax call and your program should work.

When calling from ajax, ModelAndView will not work. You need to return the employee object as json by marking the the return type with annotation #ResponseBody
#RequestMapping(value="/employee_edit", method=RequestMethod.GET)
public #ResponseBody Employee RegitrationEdit(#RequestParam("eid") long eid)
{
Employee employee=employeeService.getEmployee(eid);
return employee;
}
After that upon successful call, you will get the response inside success callback.
$.ajax({
type:"GET",
url:"employee_edit?eid="+eid,
success: function(data) {
//here data is the employee object
//process it here and redirect using window.location
}
});

Related

My ajax doesn't call the method on the controller

I have an on my index page(thymeleaft page), with a click to call a function in ajax and this ajax method to call a method in the controller, but the method in the controller is not called.
href:
<span></span>Add
ajax:
function addproductcart(id){
$.ajax({
type : "GET",
url : "/addproductcart/"+id,
success : function(result){
$('#headsearchproduct').val(result.id);
}
});
};
controller:
#GetMapping("/addproductcart/{id}")
public ResponseEntity<Produtocarrinho> adicionarprodutocarrinho(#PathVariable("id") Long id) {
Produtocarrinho produtocarrinho = new Produtocarrinho();
Produtos produto = produtoRepository.findById(id).get();
produtocarrinho.setId(produto.getId());
produtocarrinho.setFoto1min(produto.getFoto1min());
produtocarrinho.setQuantidade("1");
produtocarrinho.setValor(produto.getPrecoNovo());
ResponseEntity<Produtocarrinho> responseEntity = new ResponseEntity<Produtocarrinho>(produtocarrinho, HttpStatus.OK);
return responseEntity;
}
I had already made a method exactly like that on another page of this project and it worked very well, and I already debugged it and saw that it is not called the controller method, does anyone know where is wrong?
I solved this, the problem was in the spring security blocking this request

AspNetBoilerplate Ajax repose error despite 200 response code

Im having some unexpected problems with a ajax call within the aspnetboilerplate system.
I want to return an array to populate a select list,
The ajax call fires correctly and hits the controller. The controller returns the results as a model successfully, except it continually hits an error.
here is my controller action:
public async Task<List<DialectDto>> GetAllDialects(int Id)
{
var language = await _languageAppService.GetLanguage(Id);
return language.Dialects;
}
Here is my ajax call
var languageId = $(this).val();
abp.ui.setBusy('#textContainer');
$.ajax({
url: abp.appPath + 'Language/GetAllDialects?Id=' + languageId,
type: 'POST',
contentType: 'application/json',
success: function (content) {
abp.ui.clearBusy('#textContainer');
},
error: function (e) {
abp.ui.clearBusy('#textContainer');
}
});
Inspecting the return object in javascript clearly shows a 200 result with all the data in the responsetext property.
Other posts suggest that the content type isnt specified correctly and this is likely the a json parse error. Ive tried setting the dataType property to both 'json' and 'text' but still get the same response
I just had the same problem in one project. I'm using AspNet Boilerplate on a web .NET5 project.
Just like in your case I had a call to a controller method in my JavaScript code that returned 200 code, while in JS I had a parse error and then the "success" code was not executed. To solve the problem I changed the return value of my controller method. I used to return an IActionResult value (i.e. the Ok() value for ASP.NET). Then I changed the return value to another object (a DTO in my case) and everything went right afterwards. For reference:
Before (not working):
[HttpPost]
public async Task<IActionResult> Method([FromBody] YourClass input)
{
// method logic
return Ok();
}
After (working):
[HttpPost]
public async Task<DtoClass> Method([FromBody] YourClass input)
{
// method logic
return dtoClass;
}
I also tested that returning a JsonResult class works with the framework just like this (e.g. return new JsonResult(result)).
Hope this helps somebody else in the future :)

How do I cause an MVC controller to redirect the user from an ajax call?

I am sending an array as the "data" value (parameters) of an ajax call to an MVC controller. The controller should then redirect the user to a new page but it does not. Instead I can see in the Preview window that the View is being returned but through the ajax return. I am not sure if the way I am approaching this is correct because I seem to be having a hard time finding good examples to follow. I wanted to avoid an Html.ActionLink because I will have about 20 parameters to pass to the controller.
Here is the function that sends the array to the controller:
submit: function () {
var data = {
"ReqDepartment": (viewModel.reqDepartment === null) ? null : viewModel.reqDepartment,
"EquipmentGroup": (viewModel.equipmentGroup === null) ? null : viewModel.equipmentGroup,
"SiteCode": (viewModel.site === null) ? null : viewModel.site.SiteCode,
}; //header
$.ajax({
type: "POST",
url: "/ArctecLogisticsWebApp/Requisitions/ReqsSummary/",
data: data,
traditional: true
});
}
Here is the controller, ReqSearchCriteria is a ViewModel :
public ViewResult ReqsSummary(ReqSearchCriteria criteria)
{
return View("ReqsSummary", requisitionsRepository.GetReqsAdvancedSearch(criteria));
}
The controller is returning the View in the ajax call. Should I use a different approach to send an array to the controller?
ajax calls won't redirect by themselves. what you need to do is return json from the controller to the view with the result of the action and if the action is successful then redirect
$.ajax({
type: "POST",
url: "/ArctecLogisticsWebApp/Requisitions/ReqsSummary/",
data: data,
traditional: true,
success: function(result){
if(result.Success){
window.location = '#Url.Action('Action', 'Contorller')';
}
}
});
Edit:
The controller method you have will work. It should be a different name from the form you are redirecting from to eliminate confusion. Through data you can pass any information that you need.
data: { id: $('.id').val() },
something like this will pass whatever value is in the field with class id. then on your controller create the model for the view and return view. I use ajax calls everywhere, they are incredibly useful. Please let me know if you have any other questions.
You don't have to check for a result in your success/done handler and then do the redirect manually. You can actually return a JavascriptResult from your controller and it will redirect for you:
$.ajax({
type: 'post',
url: '/Home/DoStuff'
});
[HttpPost]
public ActionResult DoStuff()
{
return JavaScript(string.Format("window.location='{0}';", Url.Action("About")));
}
If you wanted to get fancy you could even create a new ActionResult type that took care of the formatting for you. Or you could detect if it is an AjaxRequest and determine if you should do a RedirectToAction or a JavaScript result.

Controller action method call have the parameter as NULL while calling javascript in MVC3

I use MVC3.
I have `
function userLocation_change()
{
var text = $("#userLocation").val();
alert(text);
var url = '#Url.Action("GetAllLocations", "Home")';
var data = text;
$.post(url, data, function (result) {
});
}
`
Here is my controller action:
public JsonResult GetAllLocations(string userlocation)
{
///...some code...
return Json(..Something.., JsonRequestBehavior.AllowGet);
}
The problem is whenever the controller function is called "userlocation" parameter does have a NULL value. I want the data value would be passed to the controller action.
Could somebody plz tell me why this happens? Any update would be much appreciated.
Thanks.
You need to pass the parameter to the #Url.Action specifically via this overload method for Url.Action. You can use the RouteValueDictionary inline constructor with to instantiate.
Edit: realize now that you need that link to be populated at run time, but the Url.Action method generates the link at render time. I would suggest adding it to the query string and then reading it from the query string in your controller method. I suspect there is a more elegant way.. but I know this works.
something like: var url = '#Url.Action("GetAllLocations", "Home")?userlocation=' + $("#userLocation").val();
Modify your jQuery post function call as:
$.post(
url,
{ userlocation: text },
function(result){
....
});
This is because, you have to send data to the Controller's action method using JavaScript literal. You can view the full listing of different ways to call Controller's action using JavaScript here: http://www.asp.net/ajaxlibrary/jquery_posting_to.ashx
Your action has a string input parameter named userlocation, hence while sending the data to the action, you should specify this, like done in the code below.
Here I am using data: { userlocation: text},
function userLocation_change()
{
var text = $("#userLocation").val();
var url = '#Url.Action("GetAllLocations", "Home")';
$.ajax({
url: url,
type: 'POST',
data: { userlocation: text},
success: function (result) {
}
});
}
Hopes this solves your null problem.

Is it possible to pass a generic model to a JsonResult action from an ajax call?

I'm creating a javascript function that will invoke ajax call to validate the model of a form.
function ValidateModel(formID) {
$.ajax({
url: '/Custom/ValidateModel',
type: 'POST',
data: $('#' + formID).serialize(),
dataType: 'json',
processData: false,
success: function (data) {
// code remove for brevity
}
});
}
That will be handled by this Action in the CustomController
[HttpPost]
public ActionResult ValidateModel(CustomModel model)
{
if (!ModelState.IsValid)
{
// code remove for brevity
}
return Json(customObject, JsonRequestBehavior.DenyGet);
}
If I will pass a form with CustomModel object the auto binding works just fine. What I want to create is a generic handler on the server to validate the model. I want to achieve it with something like this:
public ActionResult ValidateModel(GenericModel model)
{
}
so that when I can pass different forms with different model types on the server.
thanks!
Could you use an interface that all your models implement and have
public ActionResult ValidateModel(IViewModel model)
{
}
You'd be able to pass any model that implements the IViewModel interface.
Or maybe you could use an abstract base class?

Resources