JQuery form.submit() not calling controller method - javascript

I have two click methods in my javascript as follows. Method 1 is hitting the controller method but after that when clicking on a button for Method 2, it is not hitting the controller. Here I dont want to use $.ajax call for submit. I tried different ways but am not sure why method 2 is not hitting the controller. Appreciate any inputs. Thanks.
Method 1:
$("#selectAll").click(function () {
var familyDetailsForm = $("#family_details");
var enrollmentSetupId = $("#enrollmentSetupId").val();
var eId = $("#eId").val();
var url = "";
if($("#isDental").val() == "true"){
url = GlobalVars["app_url"] + "/shop/search/addAllDentalPlans?enrollmentSetupId=" +
enrollmentSetupId+"&eId="+eId;
}
else {
url = GlobalVars["app_url"] + "/shop/search/addAllHealthPlans?enrollmentSetupId=" +
enrollmentSetupId+"&eId="+eId;
}
familyDetailsForm.attr("action", url);
familyDetailsForm.submit();
});
Method 2:
$("#removeAll").click(function () {
var remove_familyDetailsForm = $("#family_details");
var remove_enrollmentSetupId = $("#enrollmentSetupId").val();
var planType = $("#planKind").val();
var url = "";
if($("#isDental").val() == "true"){
url = GlobalVars["app_url"] + "/shop/search/removeAllDentalPlans?
remove_enrollmentSetupId=" +remove_enrollmentSetupId+"&planType="+planType;
}
else {
url = GlobalVars["app_url"] + "/shop/search/removeAllHealthPlans?
remove_enrollmentSetupId=" +remove_enrollmentSetupId+"&planType="+planType;
}
remove_familyDetailsForm.attr("action", url);
remove_familyDetailsForm.submit();
});
Controller:
#RequestMapping(value = "removeAllHealthPlans", method = RequestMethod.POST)
public String removeAllHealthPlans(HttpSession session, HttpServletRequest request, Model model)
throws Exception {

First check if your method is properly mapped. It should be rather
#RequestMapping(value = "/removeAllHealthPlans", ...)
This is of course assuming that your controller is mapped as /shop/search

Related

Pass a value to my controller with $.get() javascript to my controller method

Here is my goal:
I'm trying to display the details of an event in my modal.
For that, I execute a javascript script which returns to the "GetEventsDetails" method of my "Event" controller with the id of the event.
When I debug with Chrome, I see the id pass except that in my controller, the value is always 0.
I do not really understand why, I checked a lot on the net and everything seems right on my side!
Is it because I do not use an ajax call?
Thank you in advance!
function GetEventsDetails(id) {
//$('#myModal').find('.modal-title').text("Details ");
$.get("#Url.Action("GetEventsDetails", "Events")/" + id,
function (data) {
$('.modal-body').html(data);
})
$('#myModal').show();
}
</script>
}
[Authorize]
[HttpGet]
public async Task<ActionResult> GetEventsDetails(int Zkp)
{
ViewBag.sessionv = HttpContext.Session.GetInt32("idMember");
FileMakerRestClient client = new FileMakerRestClient(serverName, fileName, userName, password);
var toFind = new Models.EventsLines { Zkp = Zkp };
var results = await client.FindAsync(toFind);
bool isEmpty = !results.Any();
if (isEmpty)
{
return View();
}
Models.EventsLines oEventViewModel = new Models.EventsLines();
oEventViewModel = results.ToList().First();
Console.WriteLine(oEventViewModel);
return PartialView(oEventViewModel);
}
<script>
function GetEventsDetails(id) {
//$('#myModal').find('.modal-title').text("Details ");
var urlpath = "/ Events / GetEventsDetails /" + id;
$.get(urlpath, function (data) {
$('.modal-body').html(data);
});
$('#myModal').show();
}
</script>
And Your Controller
public async Task<ActionResult> GetEventsDetails(int id)

Ajax call to ASP.NET MVC Controller Returns 404 when Json Length is too Long

I have a simple ajax call which is passing a json string to a controller action and if the content portion of the json is too long, or the json string in general, the server returns a 404, if I shorten the content, it the request resolves and completes correctly.
I thought it was do to the 8k limit of Microsoft's JavaScriptSeralizer, but I have updated the MaxJsonLength, with no luck. Can somebody please tell me what's going on here?
Here is my ajax request (Note: This is using Knockout.js)
self.updatePost = function () {
var postToUpdate = ko.toJS(self.selectedPost);
postToUpdate.Content = $("#wmd-input").val();
console.log(postToUpdate);
$.getJSON('/blogs/posts/update', {post: ko.toJSON(postToUpdate)}, function(post) {
if (post) {
// remove the selected post and add the updated post
self.posts.remove(self.selectedPost());
var updatedPost = new Post(post);
self.posts.unshift(updatedPost);
self.selectedPost(updatedPost);
$("#ghost-list li:first").trigger('click');
// show alert
}
});
};
The C# Controller Action
public JsonResult Update(string post)
{
var seralizer = new JavaScriptSerializer();
seralizer.MaxJsonLength = int.MaxValue;
seralizer.RecursionLimit = 100;
var selectedPost = seralizer.Deserialize<Post>(post);
var student = students.GetStudentByEmail(User.Identity.Name);
var blog = db.Blogs.SingleOrDefault(b => b.StudentID == student.StudentID);
var postToUpdate = blog.BlogPosts.SingleOrDefault(p => p.ID == selectedPost.ID);
if (postToUpdate != null)
{
// update the post fields
postToUpdate.Title = selectedPost.Title;
postToUpdate.Slug = BlogHelper.Slugify(selectedPost.Title);
postToUpdate.Content = selectedPost.Content;
postToUpdate.Category = selectedPost.Category;
postToUpdate.Tags = selectedPost.Tags;
postToUpdate.LastUpdated = DateTime.Now;
if (selectedPost.Published)
{
postToUpdate.DatePublished = DateTime.Now;
}
// save changes
db.SaveChanges();
var jsonResult = Json(seralizer.Serialize(selectedPost), JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
return Json(false, JsonRequestBehavior.AllowGet);
}
Have you tried using the post method:
$.post('/blogs/posts/update', {post: ko.toJSON(postToUpdate)}, function(post) {
if (post) {
// remove the selected post and add the updated post
self.posts.remove(self.selectedPost());
var updatedPost = new Post(post);
self.posts.unshift(updatedPost);
self.selectedPost(updatedPost);
$("#ghost-list li:first").trigger('click');
// show alert
}
}, 'json');
Try this at web config
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="500000000"/>
</webServices>
</scripting></system.web.extensions>

Updating view by calling Action Method from Javascript

I have a javacript Like this:
<script>
function GetFromDate() {
var dt1 = document.getElementById('fromDate').value;
var dt2 = document.getElementById('toDate').value;
var url = "Statistics/Excel/" + dt1 + "!" + dt2;
window.location.href = url;
return false;
};
</script>
and in controller my ActionResult is like this:
public ActionResult Excel(string id)
{
\\ View Creation
if(SomeLogic)
{
\\Excel Download Options
}
return View(viewModel);
}
Though it is perfectly working with the Excel Downloading option but it is not returning the View. Any Suggestions?
For more information "viewModel" object contains the perfect data to be displayed.
If your response is returning a file download, then this counts as your Http response, you aren't able to then do a redirect in the same action.

Getting null value to controller's action passing from javascript using jquery

What I tried in my project is like passing checkbox's selected value as a comma separated string to json of my controller.. but i'm not getting a value to the json action.. it shows null over there.
How can I do this? Please help me
function getIds(checkList)
{
var idList = new Array();
var loopCounter = 0;
jQuery("input[name=" + checkList + "]:checked").each
(
function()
{
idList[loopCounter] = jQuery(this).val();
loopCounter += 1;
}
);
alert(idList);
jQuery.getJSON("/Photos/CheckForIdsJson", { idList: idList });
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult CheckForIdsJson(Int32[] idList)
{
JsonResult result = new JsonResult();
result.Data = idList;
return result;
}
You can have a look at this post : AJAX Post of JavaScript String Array to JsonResult as List<string> Always Returns Null? or this one : Send list/array as parameter with jQuery getJson . It seems that you have to indicate traditional: true in your ajax call.
Use this in your script :
var did ='',
$("#tbl").find("input:checkbox").each(function (i) {
if (this.checked == true) {
did += $(this).val() + ",";
}
});
alert(did);
if (did == "") {
alert("Please Select");
return;
}

How to replace function params?

I'm using the following code to make ajax call where the form data is passed as params.
//ajax call
function restServiceCall(origin,destination,tripType,dateDepart,dateReturn){
dataString = 'origin='+ origin + '&destination=' + destination + '&tripType='+tripType;
$.jsonp({
"url": flightURL,
callbackParameter:jsonpCallBack,
data: dataString,
beforeSend:function(){$('#loadingdiv').show()},
"success": function(data) {
if(data.error != null){
$('#errtitle').html('<h2 class="pgtitle">Error !! '+data.error+'</h2>').show();
$("#displaydiv,loadingdiv").hide();
}else{
renderData (data,dateDepart,dateReturn);
}
},
"error": function(xOptions, textStatus) {
$('#errtitle').html('<h2 class="pgtitle">Sorry the service you are looking for is currently unavailable</h2>').show();
$("#displaydiv,loadingdiv").hide();
}
});
}
Besides making the call from form I also use it in the following function wherein I just need to pass either the dateDepart/dateReturn as params.
//for pagination
$('.pagenation a').bind('click',function(){
var numDays = 7;
var self = $(this);
var dateTemp = self.parents(':eq(1)').attr('id')=="onewaytripdiv"? parseDate(dateDepart):parseDate(dateReturn);
if(self.hasClass('left')){
var tempDepDate = removeNumOfDays(dateTemp,numDays);
}else{
var tempDepDate = addNumOfDays(dateTemp,numDays);
}
var changedDate = tempDepDate.getDate()+' '+cx.monthNamesShort[tempDepDate.getMonth()]+' '+tempDepDate.getFullYear();
if(self.parents(':eq(1)').attr('id')=="onewaytripdiv"){
dateDepart = changedDate;
}else{
dateReturn = changedDate;
}
restServiceCall(origin,destination,tripType,dateDepart,dateReturn);
});
I would like to remove the params in the function call, as the params may vary. Please suggest an alternative to pass the params.
How about passing an array of parameters instead? And then pass another value, such as an integer to indicate to the function what to expect in it's parameter array.
e.g
restServiceCall(myParams, 0);

Categories

Resources