passing array of values from view to controller using ajax - ajax

I have a form in my view page.it contains 5 text boxes,one search button.while the user enters values in textbox(Entering all fields are not mandatory)and click on the search button,the values I have to store it in an array and pass it to the controller and depending upon the search results i have to display the results of those searched records.
I am able to store the searched values in an array,now i want how to pass this array to the controller and how to access these values in the controller.

as Jose referred , your request may look like this :
$("#submit").click(function () {
var searchData = new Array();
$(".search-input").each(function () {
searchData.push($(this).attr('value'));
});
$.ajax({
type: "POST",
url: "/Home/Index",
data: {"searchData" : searchData},
success: function (data) {
// do something on success
},
traditional: true,
dataType: "json"
});
return false;
});
and your controller action could be :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index([Bind(Prefix="searchData")] List<string> searchData)
{
return Index();
}
and your form have to have markup like this:
<form id="myform">
<input type="text" class='search-input' />
<input type="text" class='search-input' />
<input type="text" class='search-input' />
<input type="text" class='search-input' />
<input type="submit" id="submit" />
</form>

Use ajax. If jQuery is an option you could write something like this
$(form).submit(function()
{
var ;
$.ajax({
type: "POST",
url: "/Controller/Action",
data: JSON.stringify(_yourArrayObject),
success: function(data){
alert(data.Result);
},
dataType: "json"
});
})

Related

Ajax response in a text field

I have this ajax form that gets the value of the user field, I need the answer of everything of all the process I do in the php file to be seen in the same user field but it doesn't work how can I do this thanks
<form method="post" id="form">
<input type="text" id="user" name="user"/>
<input type="button" id="btn" value="button" />
</form>
$.ajax({
type: "POST",
url: url,
data: $("#form").serialize(),
success: function(data) {
$('#user').html(data); //print answer in text field
}
});
You use the val() method to set text in an textbox
$.ajax({
type: "POST",
url: url,
data: $("#form").serialize(),
success: function(data) {
$('#user').val(data); //print answer in text field
}
});

AJAX Post to MVC Controller model every time empty

I am trying to send some data from a modal dialog to my controller with Ajax. But my modelfields are always null, but I enter my actionmethod in the controller.
This is a shortend version of my cshtml-file.
#model anmespace.MyModel
<form method="post" id="formID">
...
<div class="row">
<div class="col-md-5">#Resource.GetResource("MyModal", "Firstname")</div>
<div class="col-md-7"><input type="text" class="form-control" id="firstname" value="#Html.DisplayFor(model => model.FirstName)"></div>
</div>
...
<input type="submit" class="btn btn-primary" value="Submit" />
</form>
<script>
$("#formID").on("submit", function (event) {
var $this = $(this);
var frmValues = $this.serialize();
$.ajax({
cache: false,
async: true,
type: "POST",
url: "#Url.Action("ActionName", "Controller")",
data: frmValues,
success: function (data) {
alert(data);
}
});
});
</script>
Sorry MVC/Ajax are really new for me.
If you want to bind the form data to model then, the names of HTML elements should match with Model properties.
Note: name attribute value of html input field should match to the property of a model.
When you use form and submit button then it will try to reload the page by posting data to the server. You need to prevent this action. You can do this by returning false on onSubmit event in the Form element.
When you use jquery, do not forget to keep the ajax call/events inside the $(document).ready(function(){}) function.
I have written a simple code which takes First Name as input and makes an ajax call on clicking on submit button.
Html & Jquery Code:
<script>
$(document).ready(function() {
$("#formID").on("submit", function(event) {
var $this = $(this);
var frmValues = $this.serialize();
$.ajax({
cache: false,
async: true,
type: "POST",
url: "#Url.Action("PostData", "Home")",
data: frmValues,
success: function(data) {
alert(data.FirstName);
}
});
});
});
</script>
<div>
<form method="post" id="formID" onsubmit="return false;">
<input id="FirstName" name="FirstName"/>
<input type="submit" value="submit" />
</form>
</div>
My Model :
public class Person
{
public string FirstName { get; set; }
}
Action Method:
public ActionResult PostData(Person person)
{
return Json(new { Success = true, FirstName = person.FirstName });
}
Output:

MVC - Sending List of Values to AJAX call

I have a Modal that opens & gives User options to check some checkboxes. When the User checks checkboxes of his choice. I want to send all the values of checkboxes & call AJAX method.
I want to send values of selected checkboxes to the Controller method.
Here is my Code :-
// These are dynamic checkboxes - This is just an e.g
<input type="checkbox" name="name" value="Code">
<input type="checkbox" name="name" value="Code1">
<input type="checkbox" name="name" value="Code2">
<input type="checkbox" name="name" value="Code3">
// onClick event of Button
jq.get('/Controller/getData', function (data) {
jq('#placeHolder').html(data);
});
// Controller
[HttpGet]
public ActionResult getData()
{
return PartialView("_pagepartial");
}
To get the values of the checked checked boxes and add to an array
var array = [];
$('input:checked').each(function() {
array.push($(this).val());
}
And to pass to you controller
$.ajax({
type: "GET",
url: '#Url.Action("getData", "Controller")',
dataType: "html",
traditional: true,
data: { values: array},
success : function (data) {
$('#placeHolder').html(data);
}
});
assuming you controller method is
public ActionResult getData(string[] values)
{
// return some partial view based on values
}

Cakephp :How to post data on two actions

I am trying to post data by a form.
I need to submit the form on other website and have to save the data in my database as well. I tried my best but did not find the solution for this.
Here is my form:
<form class="formaction" action="http:www.demo.com" method="post">
<input type="text" value="1" name="quantity" class="form-style pull-left">
<input type="hidden" name="stock" value="1100">
<input type="submit" value="Add" style="display: block;" class="button-style">
</form>
Case I:
In this case form is submitted to www.demo.com , but it causes error at mystagingserver/addtotrolley
Ajax function:
$('.formaction').submit(function() {
$.ajax({
type: 'POST',
url: 'mystagingserver/addtotrolley',
data: {
quantity: $( "input[name$='quantity']" ).val(),
stockcode: $( "input[name$='stockcode']" ).val()
}
});
});
Case II:
In this case Form is not submitted to www.demo.com but ajax works properly, and it saves my data to database from mystagingserver/addtotrolley
$('.formaction').submit(function() {
$.ajax({
type: 'POST',
url: 'mystagingserver/addtotrolley',
data: {
quantity: $( "input[name$='quantity']" ).val(),
stockcode: $( "input[name$='stockcode']" ).val()
}
});
return false;
});
From Case I what I gathered is, when the user clicks Submit, it makes an ajax call. And immediately attempts to submit the form to www.demo.com. Meaning you are moving away from the page and probably losing the connection. What error message are you getting exactly?
The best approach would be to make an AJAX call to your staging server. If it succeeds only then proceed with the regular form submission or make another AJAX post request to the third party domain.
Something like below would be ideal:
$('.formaction').submit(function() {
$.ajax({
type: 'POST',
url: 'mystagingserver/addtotrolley',
data: {
quantity: $( "input[name$='quantity']" ).val(),
stockcode: $( "input[name$='stockcode']" ).val()
},
success: function(resp) {
$.ajax({
type: 'POST',
url: 'http:www.demo.com',
data: {
quantity: $( "input[name$='quantity']" ).val(),
stockcode: $( "input[name$='stockcode']" ).val()
},
success: function(resp) {
alert("Successfully submitted to both!");
}
});
}
});
return false;
});

Pass ASP MVC3 textbox value to Ajax call

I have a simple ASP MVC3 #Html.TextBox that I'm using to input search criteria. However, I need to append the value to the URL in an Ajax call as a query string. How would I go about this? Below is the HTML in the view:
<div class="editor-field">
#Html.TextBox("searchString")
<span onclick='GetCompName(searchString);'>
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" />
</span>
</div>
And here is the Ajax
function GetCompName(searchString) {
var request = $.ajax({
type: 'POST',
url: 'http://quahildy01/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,' + searchString + ')',
dataType: 'html',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});
}
I will also want to output the returned value into another text box. If anyone knows how to do that that would be really helpful as well. Thanks!
the basic problem with your code is the searchString in onclick='GetCompName(searchString); always gonna be literally "serchString", you must specified the parameter in base the value in the input, like this $('.searchbox').val()
keep your javascript unobstructive.
HTML code
<div class="editor-field">
#Html.TextBox("searchString", null, new { #class = "serachbox" })
<span class="searchbox-trigger">
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" />
</span>
</div>
Set de handler for the event span click
$(document).ready(function() {
$('.searchbox-trigger').click(GetProgramDetails);
});
and your ajax request
function GetProgramDetails() {
var request = $.ajax({
type: 'POST',
url: 'http://quahildy01/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,' + $('.searchbox').val() + ')',
dataType: 'html',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});
}

Resources