Asp.net MVC Checkbox Event HTTPPOST ServerSide - c#

net mvc5 form and Using checkbox.
My condition is i need to Call HTTPPOST action immedaitely after selecting the checkbox(true)
Its something like HTTPPOST action should be called immediately after selecting the checkbox.
I need to pass Model as well to the HTTP Post.
can you please let me know whats the desired way to get this done ?

I'd recommend using jquery to achieve this. Assuming your checkbox is nested in a form, you can use:
$(function () {
$('#CheckBoxName').change(function () {
$(this).closest("form")[0].submit();
});
});
This will trigger a postback, calling the appropriate HttpPost method and sending the model as a parameter.

You should use javascript to react on a change of the checkbox then posting via ajax.
Here is an exemple :
$('#checkbox').change(function(){
if (this.checked){
var jsonModel = '#Html.Raw(Json.Encode(Model))';
$.ajax({
type: 'post',
url: '#Url.Action("UrlOfPostAction")',
data: { Model: jsonModel},
dataType: 'json',
success: function (res) {
//Do something
}
//manage errors
});
}
});

Related

Return view after ajax post to controller

I'm sending some json data with ajax by post
function SendF() {
$.ajax({
url: '#Url.Action("Summary")',
type: 'POST',
data: JSON.stringify(flags),
contentType: "application/json;charset=utf-8",
success: function() {
},
error: function() {
alert("Oops! We've experienced a connection problem!");
}
});
}
to my controller
[HttpPost]
public ActionResult Summary(List<string> flagsChecked)
{
[...]
return View(flags);
}
and tried returning a view with data I've processed, but I guess it's not gonna happen since ajax is all about asynchronous http requests. How do I change my code to be synchronous?
The whole idea behind using ajax is to give the user the partial page update experience. If you are making an ajax call and once that is done and you are doing a redirect to another page, it does not give the partial page update experience to user. It looks very similar to the normal form submit(full page submit).
If you absolutely have to send the data to server via ajax , but want to do the redirect after the ajax call is successfully finished, you can do that using javascript in the success or done callback event on the $.ajax method.
All you have to do is, set the location.href property to the new url.
var flags = ["aa", "bb", "cc"];
$.ajax({
url: '#Url.Action("Summary")',
type: 'POST',
data: JSON.stringify(flags),
contentType: "application/json;charset=utf-8"
}).done(function(res) {
window.location.href = res.newUrl;
}).fail(function(xhr, a, error) {
console.log(error);
});
This assumes that your server action method returns a JSON response with the newUrl property which contains the url you want to redirect to .
[HttpPost]
public ActionResult Summary(List<string> flagsChecked)
{
return Json(new { newUrl = Url.Action("Index","Home") });
}
One way to do this would be to send the request to the controller via ajax and then render a partial view on your page. The easiest way would be to use the built in ajax helpers in ASP MVC. Here is a link to another post that gives a pretty good overview:
How to render partial view in MVC5 via ajax call to a controller and return HTML

How to call an Action method using ajax for a button click which is in partial view in MVC?

I'm new to MVC. I got a situation where I need to pass a parameter from view to controller on the button click (the button is in partial view), which then renders another partial view in the same page.
Steps followed:
I used jquery button click event for the button of partial view.
I made an ajax call to pass the parameters from my view to the controller.
The following is my code:
$(document).on("click", "#btninPartialView", function(e){
var data = $("txtinPartialView").val();
$("#mainPageContainer").load("/Controller/Action", data, function(){
$.ajax({
//url: #Url.Action("Action", "Controller"),
type: GET,
data: {
id: data
},
success: function(){
}
error: function(){
}
})
}
})
Problem:
The problem is that, the data I'm received in the action method is null.
Please let me know if I'm missing anything.
Thanks in advance.
$(document).on("click", "#btninPartialView", function(e){
var data = $("txtinPartialView").val();
$.ajax({
url: "/Controller/Action",
type: GET,
data: {
id: data
},
success: function(result){
$("#mainPageContainer").html(result);
}
error: function(){
})
})
This should work.
Please check with the arguments your Action method is accepting.
for example if signature is
public ActionResult Action1(string name)
then you need to pass the data as
var data = { name : $("txtinPartialView").val() }
The problem is that you are mixing both jquery ajax and load function, load function sends an ajax call behind the scenes, so you need to use one of them, not both, so try like:
$(document).on("click", "#btninPartialView", function(e){
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: GET,
data: {
id: $("txtinPartialView").val()
},
success: function(response){
$("#mainPageContainer").html(response);
},
error: function(){
}
});
});

How to refresh my Partial View after Ajax Post in MVC?

So basically I'm trying to show some Profile Data in my MVC Application.
Right now, everytime I click on a date on my Telerik Kendo Calendar, I can refresh the whole page and update the data I want.
However, instead of refreshing the whole I just want to refresh the partial views that shows only the data that updates after selecting the date.
Index.cshtml
<!--CODE-->
#Html.Partial("_WorkingTimeData")
<!--CODE-->
_WorkingTimeData.cshtml
var workedTime = ViewData["WorkedTimeToday"];
var hoursPerDay = ViewData["HoursPerDayContract"];
<p>You worked #workedTime hours</p>
<p>Hours Per Day (Contract) #hoursPerDay Hours</p>
Yes, right now I'm ViewDatas and it works.
This is the ajax code in Index.cshtml
$.ajax({ url: '/Profile/Index',
dataType: "json",
type: "POST",
data: JSON.stringify(10),
success: function(returl){
alert('It worked');
location.href=returl.Url;
},
error: function(jqXHR,responseText,textStatus){ alert(jqXHR.responseText) } });
Controller
[HttpPost]
public ActionResult Index(string number){
//THINGS TO DO
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Profile");
return Json(new { Url = redirectUrl });
}
Well I'm very new to this, and I've been doing my research. However I still have some questions:
- Do I need to create a post method for _WorkingTimeData instead of Index like I have?
- Do I need to create a ViewModel for the Partial View?
Thanks
EDIT NUMBER 2 FOR VISHAL:
This didn't work at all, not even an alert, because, strangely, it doesn't recognise the calendar...
$("#calendar").kendoCalendar({
change : function() {
$.ajax({
url: "/Profile/WorkingTimeData",
type: "get"
}).done(function(data) {
$("#profile-timeline").html(data);
});
}});
It says $("#calendar").kendoCalendar is not a function (Telerik says that it's this way)
As for this, it reached the controller but didn't update anything:
function change() {
alert("Escolheste outro dia");
var calendar = $("#calendar").data("kendoCalendar");
var current = calendar.current();
alert(current);
$.ajax({
url: "/Profile/WorkingTimeData",
type: "get"
}).done(function(data) {
$("#profile-timeline").html(data);
});
}
I think it's because of the profile-timeline... It's a div in my view
Do I need to create a post method for _WorkingTimeData?
Yes, you need to create. But, Get would be fine too.
Do I need to create a ViewModel for the Partial View?
Not needed. If required you can create.
But, by looking at your partial view you are just using ViewData[""]. So, you need not to create any ViewModel.
Just create a method in Controller returning _WorkingTimeData PartialView.
And call that method by JQuery ajax on your DatePicker change event and replace the contents of the Div.
For example.
Controller
public PartialViewResult WorkingTimeData()
{
ViewData["WorkedTimeToday"]="NEW VALUE";
ViewData["HoursPerDayContract"] = "NEW VALUE";
return this.PartialView("_WorkingTimeData");
}
JavaScript
$("DATEPICKERELEMENT").change(function() {
$.ajax({
url: "/CONTROLLER/WorkingTimeData",
type: "get"
}).done(function(data) {
alert(data);
$("#divisionIdContainingPartialView").html(data);
}).fail(function() {
alert('error');
});
});
I wrote a post that details why you need to break the logic of thinking about partial views client-side. If you're interested you can find it here.
The TL;DR version is simply, all you have client-side is HTML. There's no knowledge about what was or was not rendered to the response via a partial view. As a result, the real question is "How do I change a portion of my HTML page based on an AJAX response?". In the simplest form, you simply select some element on the page and then alter its inner HTML. You can do that with some custom HTML created client-side or you can actually pass back an HTML document as your AJAX response and then insert that.

ASP.NET MVC submit empty string to WebApi Controller on jquery serialize()

I'm trying to POST data from ASP.NET MVC View to WebApi Controller via j Query $.post(), but I'm always receiving just empty string (what's interesting - this work fine with Web Forms).
Here is JS.
$("#searchbtn").click(function () {
var ser = $("div#hotels").serialize();
$.post('/api/hotelsavailablerq', { '': ser });
});
Here is how ApiController signature look like:
[HttpPost]
public void PostHotelsAvailableRq([FromBody] string q)
View using just pure HTML forms - div, select, input type=text. Nothing Binded from model.
try another:
$.ajax({
url: '/api/hotelsavailablerq',
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json'
data: JSON.stringify(ser)
});
Please try the below code to hit the controller. Make sure there is hotelsavailablerq action method in api controller.
$("#searchbtn").click(function () {
$.ajax({
url: '/api/hotelsavailablerq',
type: 'POST',
data: $('div#hotels').serialize(),
success: function (result) {
});});
Well, I found answer - RTFM.
When I read carefully jQuery documentation about serizlization, I found that:
1. <form> tag should exist.
2. Each control should have name attribute.
All these things has by default in web form, but in MVC I should add its manually.
Try
$.post('/api/hotelsavailablerq', { 'q': ser });
string q should be of the same type which you are sending from the jQuery.

Including an array with a serialize form - jquery

I currently have a form that I am trying to perform a post on (serializing the form), however I also want to include several checkboxes (but I don't want to include them in the form itself)
I have tried using jQuery's .post, but was unable to accomplish what I needed, any help would be greatly appreciated.
(I am using asp.net MVC 2.0 - and I figured this event would be attached to a button click)
There are several ways to accomplish this, I'll demonstrate two for you, along with an example of a Controller Action to accept the data:
Your Controller Action:
[HttpPost]
public ActionResult YourActionName(YourModel formModel, bool[] checkboxes)
{
...
}
.post Method:
//Serialize Form Data
var data = $("#yourForm").serializeArray();
//Iterates through all your checkboxes - with a specific class
$(".yourCheckboxClass").each(function ()
{
data.push({name : "checkboxes", value : $(this).val()});
});
.ajax Method:
//Build array of checkbox values
//You can use an .each here, or whatever other method you prefer
$.ajax({ type: "POST",
url: "<%= Url.Action("Action","Controller") %>",
datatype: "json",
traditional: true,
data: {
'formModel': $('#yourForm').serialize(),
'checkboxes': yourCheckboxArray
}
});
I hope this helps you accomplish what you need.
Would something like this work for you? (assuming the button is the submit button on the form)
$("#triggerButton").bind("click.me", function(e) {
var $form = $(this).closest("form");
$(".other-checkbox-class").appendTo($form);
});

Categories

Resources