Including an array with a serialize form - jquery - c#

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);
});

Related

Asp.net MVC Checkbox Event HTTPPOST ServerSide

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
});
}
});

C# MVC Calling a method in different path using AJAX

I have a HomeController in my ASP.NET MVC application in folder "Controllers". My View is in: "View/Home/Index.cshtml" (look at my figure below).
I am using Ajax to get some json file every a few second. Problem is in Ajax URL, because I really don't know and didn't find, how to tell that property, that it has to go back a few folders and then find the HomeController.
My Solution looks like this:
Here is a method in my HomeController:
[HttpGet]
public ActionResult GetRandomFeed()
{
Item i = ss.getRandomFeed();
return Json(new { Source = i.Media.Source, Avatar = i.User.Avatar, Text = i.Text, Name = i.User.Name }, JsonRequestBehavior.AllowGet);
}
My AJAX in the View:
setInterval(function () {
$.ajax({
type: "GET",
url: '/HomeController.cs/GetRandomFeed', // Of course I have tried a lots of attempts in here
contentType: "application/json;", // Not sure about this
dataType: "json",
success: function (response) {
console.log("Success :)");
},
error: function() {
console.log("Error!");
}
});
}, 2000);
All I want to get that JSON file (or can be even an array of strings) and use it in my Success function. It is a simple Slide Show and JSON contains the URLs that I want to show in the page every X seconds (just changing source of an image that is in that JSON file).
I couldn't find anything like this. How to use that URL correctly OR found something similiar for WebForms but cannot use it in MVC.
Change your AJAX URL declaration to:
url: '/Home/GetRandomFeed'
Remove the .cs
Or you can also do, assuming this view is under your controller:
url: '#Url.Action("GetRandomFeed")'
In my experience, it doesn't seem enter the function is just because the JSON return from the controller doesn't include Status = "OK"
[HttpGet]
public ActionResult GetRandomFeed()
{
...
...
return Json(new
{
Status = "Ok", ...
}

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.

Ajax post causing 2 actions to run

I'm new to MVC, and this problem has been driving me up the wall. I have some javascript that triggers a jquery ajax post when the user press the tab or enter key in the textboxes on my form:
<script type="text/javascript">
$(document).ready(function () {
$('#RmaNumber, #SerialNumber').keydown(function (event) {
if (event.keyCode == 13 || event.keyCode == 9) {
var ri = {
RmaNumber: $('#RmaNumber').val(),
SerialNumber: $('#SerialNumber').val(),
ControlName: event.target.id
}
$.ajax({
type: "POST",
url: "/Invoice/BarcodeScan",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(ri),
dataType: "json",
success: function (data) {
$('#TerminalType').text(data.TerminalType);
}
});
}
});
});
</script>
Here is what my controller looks like. I removed the code to keep things simple:
public ActionResult Index()
{
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(RepairInvoice ri)
{
}
[HttpPost]
public ActionResult BarcodeScan(string RmaNumber, string SerialNumber, string ControlName)
{
}
The ajax postback causes both the BarcodeScan and Index action to fire. I only want the Index action with the [AcceptVerbs(HttpVerbs.Post)] above it to fire if a button is pressed on my form. Is this possible, or am I on the wrong track?
Since the comments helped, I'll add as an answer for future visitors...
I can't help but notice that one of the key inputs you're looking for is the return key. Depending on how the HTML for the form and the input is set up, the return key may also be causing the form to POST as normal. So essentially:
The JavaScript code is invoking a POST to the BarcodeScan action
The HTML form is invoking a POST to the Index action
The result of the former is being ignored by the browser, since the page is being re-loaded in its entirety. But regardless of the result, the action was still invoked.
There are a couple of ways to address this:
If there is a submit input that you're otherwise using as just a button, you can change it to a button and leave the form without a submit. This works well for forms which should be JavaScript-driven only and not have a default POST action, but it's hard to tell if that applies here without knowing more.
The JavaScript code can stop the DOM event in its tracks by calling preventDefault(). Most jQuery functions have a parameter for the event, and you'd call that function on the event. This would tell the DOM to end the event so it doesn't "bubble up" to the form, the document, etc.

Making an Ajax request to a page method in ASP.NET MVC 2

I'm trying to call a page method belonging to a MVC Controller from another site, by means of:
$.ajax({
type: "GET",
url: "http://localhost:54953/Home/ola",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
console.log(data.Name);
}
});
the method code is as follows, really simple, just to test:
public ActionResult ola()
{
return Json(new ActionInfo()
{
Name = "ola"
},JsonRequestBehavior.AllowGet);
}
I've seen this aproach being suggested here, and I actually like it a lot, should it work...
When I run this, firebug gets a 200 OK, but the data received is null.
I've tried a lot of different approaches, like having the data in text (wish grants me "(an empty string)" instead of just "null") or returning string in the server method...
Can you tell me what am I doing wrong?
Thank you in advance,
João
Have you tried returning your JSON like so...
public ActionResult ola()
{
return Json(new { Name = "ola" }, JsonRequestBehavior.AllowGet);
}
Controller:
public ActionResult Ola()
{
// No need to use a custom ActionInfo type here, an anonymous type
// will be just fine:
return Json(new { Name = "ola" }, JsonRequestBehavior.AllowGet);
}
View:
$(function {
$.getJSON('/home/ola', function(json) {
alert(json.Name);
});
});
You could try returning JsonResult from the controller action method. Method signature would then be public JsonResult ola(). Hope it helps.
Thanks for all the feedback. I found out that everything I was doing was right and wrong at the same time.
the requests were all functional, but the request was being made to a different domain, wich is automatically blocked by the browsers (except IE). It's a question of security.
But since the request was meant to work on a mobile device, when i tested it there, it worked perfectly.
Once again, thanks to everyone who answered, i'll adopt some of the ideas shown here :)
if you are making an ajax call cross domain. Have you tried setting your data type to
dataType: jsonp
jquery ajax cross domain

Categories

Resources