ASP.NET MVC Jquery Ajax post form serialize? - asp.net-mvc

Ajax function
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: { model: $(this).serialize(), locations: getCheckedLocation(), reports: getCheckedReports() },
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
$('#user_operations_container').html(result);
setTimeout(function () { LoadAction('#Url.Action("GetAllUsers", "User")') }, 1000);
$("#widgets ul li a").removeClass("link_active");
$("#widgets ul li:first-child a").addClass("link_active");
}
});
}
return false;
});
});
functions that are using in ajax data attribute
function getCheckedLocation() {
var nodes = $('#tt_location').tree('getChecked');
var s = '';
for (var i = 0; i < nodes.length; i++) {
if (s != '') s += ',';
s += nodes[i].text;
}
return s;
}
function getCheckedReports() {
var nodes = $('#tt_reports').tree('getChecked');
var s = '';
for (var i = 0; i < nodes.length; i++) {
if (s != '') s += ',';
s += nodes[i].text;
}
return s;
}
HTML
<div> // there are html helpers for model (dropdownlistfor, textboxfor,...)
</div>
<div> // checkbox tree (#tt_location)
</div>
<div> // checkbox tree (#tt_reports)
</div>
Controller
[HttpPost]
public ActionResult _EditUser(UserViewModel model,string locations,string reports)
{
// model = null
// locations and reports are expected. (not null)
}
Question
Why model is null?
When I use ajax data attribute like this = data: $(this).serialize(), , It works model is not null.
How can I post model, with additional data (locations,reports).
I hope I can explain. Thanks...

Try like this:
data:$('this').serialize() + "&locations=" + getCheckedLocation() "&reports=" + getCheckedReports()
It will work.
Hope it helps

Related

select2 v4 dataAdapter.query not firing

I have an input to which I wish to bind a dataAdapter for a custom query as described in https://select2.org/upgrading/migrating-from-35#removed-the-requirement-of-initselection
<input name="pickup_point">
My script:
Application.prototype.init = function() {
this.alloc('$pickupLocations',this.$el.find('[name="pickup_point"]'));
var that = this;
$.fn.select2.amd.require([
'select2/data/array',
'select2/utils'
], function (ArrayData, Utils) {
var CustomData = function($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
};Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
var data = {
results: []
};
console.log("xxx");
for (var i = 1; i < 5; i++) {
var s = "";
for (var j = 0; j < i; j++) {
s = s + params.term;
}
data.results.push({
id: params.term + i,
text: s
});
}
callback(data);
};
that.$pickupLocations.select2({
minimumInputLength: 2,
language: translations[that.options.lang],
tags: [],
dataAdapter: CustomData
});
});
}
But when I type the in the select2 search box the xxx i'm logging for testing doesn't appear in my console.
How can I fix this?
I found the solution on
https://github.com/select2/select2/issues/4153#issuecomment-182258515
The problem is that I tried to initialize the select2 on an input field.
By changing the type to a select, everything works fine.
<select name="pickup_point">
</select>

Jquery Autocomplete in mvc if user types text which is not in autocomplete list

Jquery Autocomplete UI in mvc .. If user enter some text which is not in list it should alert not in list ....
In View:-
$("#loc").autocomplete({
source: function (request, response) {
$.ajax({
url: "/a/AutoLoc",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
if (data.length == 0) {
alert('Please select an item from the list');
document.getElementById('Loc').value = "";
document.getElementById('Loc').focus();
document.getElementById('Loc').style.border = "solid 1px red";
}
else
response($.map(data, function (item) {
document.getElementById('Location').style.border = "solid 1px black";
return { label: item.Name, value: item.Name, id: item.LocationId };
}));
}
})
},
select: function (event, ui) {
$("#locationID").val(ui.item.id);
}
});
in Controller:
public JsonResult AutoLoc(string term)
{
var result = (from r in db.S
where r.Name.ToLower().Contains(term.ToLower())
select new { r.Name, r.id }).Distinct();
return Json(result, JsonRequestBehavior.AllowGet);
}
Here suppose we enter 'a' then it will not alert any message . Though 'a' is not in list
when we enter any character which is not in autocomplete list it should alert and make that box as red.
Actually What is happening in 'data' we are getting values because in controller we are writing a query as contains or startwith 'a' so value is returned but as a individual 'a' is not in list that starts with or contains 'a'.
Try this:
$("#loc").autocomplete({
source: function(request, response) {
$.ajax({
url: "/a/AutoLoc",
type: "POST",
dataType: "json",
data: {term: request.term},
success: function(data) {
var found = $.map(data, function(item) {
return {label: item.Name, value: item.Name, id: item.LocationId};
});
if (found.length === 0) {
alert('Please select an item from the list');
$("#loc").val("");
$('#loc').focus();
$('#loc').css("border", "solid 1px red");
} else {
$('#loc').css("border", "none");
}
response(found);
}
});
},
select: function(event, ui) {
$("#locationID").val(ui.item.id);
}
});
In View:
$("#loc").autocomplete({
source: function (request, response) {
$.ajax({
url: "/a/AutoLoc",
type: "POST",
dataType: "json",
data: {term: request.term},
success: function(data) {
var found = $.map(data, function(item) {
return {label: item.Name, value: item.Name, id: item.LocationId};
});
}
});
},
change: function (event, ui) {
var referenceValue = $(this).val();
var matches = false;
$(".ui-autocomplete li").each(function () {
if ($(this).text() == referenceValue) {
matches = true;
return false;
}
});
if (!matches) {
alert('Please select an item from the list');
this.value = "";
this.focus();
this.style.border = "solid 1px red";
}
else {
document.getElementById("submitbutton").disabled = false;
this.style.border = "solid 1px black";
}
}
});
Now when we type 'a' it will alert and show the box border in red color......
This is what i wanted....

How do I get all values of checkbox those are checked using ajax/jQuery in asp.net mvc

Ajax post:
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
// var vals = [];
// $('input:checkbox[name=Blanks]:checked').each(function () {
// vals.push($(this).val());
// });
// alert(vals);
//
var checkboxData = $(':checked').val();
$.ajax({
// Check the value.
type: 'POST',
url: '/Home/Extract',
data: { 'name': checkboxData },
// contentType: 'application/json; charset=utf-8', // No need to define contentType
success: function (result) {
},
error: function (err, result) {
alert("Error in delete" + err.responseText);
}
});
});
Controller method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Extract(string[] name)
{
}
My problem is that I am getting null values in my string[] name when I use array and single checkBox values when I use other case. Any suggestions or ideas as to why the post looks good?
View:
<input type="button" id="btn" value="Extract" style="float:right "/>
#foreach (var m in (List<string>)ViewData["list"])
{
<ul>
<li>
<input type="checkbox" class="myCheckbox" name="Blanks" id="chk" value="#m"/>
<img src="#m" alt=""/>
First start by fixing your markup and remove the id="chk" from your checkboxes because you cannot have 2 elements with the same id.
Alright, and then simply generate a javascript array containing the values of the selected checkboxes and POST this array to the server:
$('#btn').click(function () {
var values = $('input[type="checkbox"].myCheckbox:checked').map(function() {
return $(this).val();
}).toArray();
$.ajax({
type: 'POST',
url: '/Home/Extract',
data: JSON.stringify({ name: values }),
contentType: 'application/json',
success: function (result) {
},
error: function (err, result) {
alert("Error in delete" + err.responseText);
}
});
return false;
});
And your controller action signature might look like this:
[HttpPost]
public ActionResult Extract(string[] name)
{
...
}
But all this would have been completely unnecessary if you had used a view model and the strongly typed Html.CheckBoxFor helper.

jQuery autocomplete completely unresponsive

This is my first time really delving into jQuery with my ASP MVC3 intranet app. I need the autocomplete to be able to reference a list of items from a database. I followed the tutorial found here and thought "ok, that looks easy"... and now after implementing the code and researching other methods and bashing my head against the keyboard for at least four hours I'm not anywhere closer to making this work that before I wrote the code.
Here is the code from the view, w/the library declarations as well. FYI - I am taking over this project, so all the other javascript/Ajax you see was written by someone else with more experience than me. I put all the code in this section just in case something else is getting in the way.
<link href="../../Content/jquery-ui-1.9.2.custom.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#BankName").autocomplete({
source: '#Url.Action("GetBanks", "AgentTransmission")',
minLength: 1
});
$(function () {
$("#drpProducerType").change(function () {
var value = $(this).val();
if (value == "SoleProprietor") {
$("#Role").val(value);
$('#DSSfields').removeClass('noSee');
$('#DSSfields').addClass('seeMe');
//alert("Role must be set to \"Sole Proprietor\" as well. Monet will do this for you!");
}
else {
//TO DO: add role stuff here as well
$('#DSSfields').removeClass('seeMe');
$('#DSSfields').addClass('noSee');
}
});
$("#Role").change(function () {
var value = $(this).val();
if (value == "SoleProprietor") {
$("#drpProducerType").val(value);
alert("Producer Type changed to \"Sole Proprietor\" as well");
}
});
});
function ChangeChannel() {
//this function called if Market Segment changes, to update the channel
var pendistcode = document.getElementById('Pendist');
if (pendistcode == null) alert('Error: Cannot find Market Segment control');
$.ajax({
type: 'POST',
url: '/AgentTransmission/GetChannel/',
data: { pendist: pendistcode.value },
success: function (data) {
// alert("success: " + data);
$('#channelName').html(data);
$('#Channel').val(data);
},
error: function (data) {
alert("failure to obtain Channel name");
}
});
CheckTerritory('channel');
} //end ChangeChannel
function CheckTerritory(category) {
//this function called when changes happen that could change the territory (inddist)
//if the channel changed, or the alignment indicator, update the Territory
if ((category == "channel") | (category == "align")) UpdateTerritory();
//only trigger if the state or zip changed on the aligned address
if ((category == "L") && ($('#AlignmentL').attr('checked'))) UpdateTerritory();
if ((category == "M") && ($('#AlignmentM').attr('checked'))) UpdateTerritory();
} //end CheckTerritory
function UpdateTerritory() {
var i = $('#INDDist').val();
var p = $('#Pendist').val();
// alert(":" + i + ":" + p + ":");
//if ((i == "") || (p == "")) return;
if (p == "") return;
if ($('#INDDist').val() == "864") {
$('#INDDist').val("701");
}
else {
if ($('#INDDist').val() == "") {
$('#INDDist').val("864");
}
}
} //end UpdateTerritory
function MoreCompanies(row) {
//if the user clicks on the plus sign, add more company rows
if (row == '3') {
$('#plus2').html(' ');
$('#row3').removeClass('noSee');
$('#row3').addClass('seeMe');
}
if (row == '4') {
$('#plus3').html(' ');
$('#row4').removeClass('noSee');
$('#row4').addClass('seeMe');
}
if (row == '5') {
$('#plus4').html(' ');
$('#row5').removeClass('noSee');
$('#row5').addClass('seeMe');
}
} //end MoreCompanies
function CompanyFields() {
} //end CompanyFields
function ShowHideTerritory() {
alert('sunshine');
} //end ShowHideTerritory
</script>
The text box the autocomplete is supposed to work on
<div class="M-editor-label">
Bank\Agency Name
</div>
<div class="M-editor-field">
#Html.TextBoxFor(model => model.BankName, new { id = "BankName" })
#Html.ValidationMessageFor(model => model.BankName)
</div>
and here is the GetBanks method from the controller. I've set a breakpoint at the first line of this method and I've never been able to get it to hit.
//GET
public JsonResult GetBanks(string search)
{
var banks = from c in db.BankListMaster.Where(n => n.BankName.Contains(search))
select c.BankName;
banks = banks.Distinct();
return Json(banks, JsonRequestBehavior.AllowGet);
}
EDIT
If I replace the current .autocomplete code with the code suggested by this method instead , I get the following error in Chrome's debugger:
Uncaught Error: cannot call methods on autocomplete prior to initialization; attempted to call method '/AgentTransmission/GetBanks'
Here's the new code, I put it in the exact same spot as what I was previously using:
$(document).ready( function() {
$('#BankName').autocomplete('#Url.Action("GetBanks", "AgentTransmission")', {
dataType: 'json',
parse: function(data) {
var rows = new Array();
for(var i=0; i<data.length; i++){
rows[i] = { data:data[i], value:data[i].BankName };
}
return rows;
},
formatItem: function(row, i, n) {
return row.BankName + ' - ' + row.Description;
},
width: 300,
mustMatch: true,
});
});
I added an extra set of closing brackets to the autocomplete which cleared this up. The widget functions properly now.
$(function () {
$("#BankNameAuto").autocomplete({
source: '#Url.Action("GetBanks", "AgentTransmission")',
minLength: 1
});
});

how to display different grids with different dataSource dynamically

I have to display KendoUI splitters dynamically depending upon the records in the database.
If i have n records in my database,I have to display "n-1" splitters.and in each partition I have to display KendoGrid with different dataSource.
I have implemented ajax to get the records from database,In the success function depending upon the length I am able to display required number of splitters.
In each splitter I put a grid like,
success: function (json) {
for (var i = 0; i < json.length; i++) {
var div = document.createElement('div');
var griddatSource = new kendo.data.DataSource({
transport: {
read: {
url: "/Home/splitter",
type: "POST",
dataType: "json"
}
},
batch: false,
schema: {
model: {
id: "iD",
fields: {
iD: { type: "number" },
name: { type: "string" },
email: { type: "string" }
}
}
}
});
$('<div id = ' + json[i].name + '>').appendTo("#splitter");
$("#" + json[i].name).kendoGrid({
dataSource: griddatSource,
selectable: "multiple",
columns: [{ field: "name", title: "Name" },
{ field: "email", title: "Email"}],
editable: false
}).data("kendoGrid");
}
$("#splitter").kendoSplitter({
orientation: "horizontal"
});
}
Now,I am able to display splitters dynamically and in each splitters I am able to load the grid,but I want to know how to use different different dataSources for different grids.
Thanks
Just use a variable :
var div = $('<div/>');
div.appendTo('#splitter');
div.someStuff();
I think you can get a short idea from this.
<script type="text/javascript">
function fnc()
{
el=document.createElement('div');
el.style.backgroundColor="red";
el.innerHTML="aaa";
document.getElementById("adiv").appendChild(el);
//document.getElementById("adiv").innerHTML=var1;
}
</script>
<div id="adiv">
qwerty
</div>
<input type="button" value="click me" onclick="fnc();">
I think this is what you mean?
function (json) {
for (var i = 0; i < json.length ; i++) {
//alert(json[i].name);
var divTag = document.createElement('div');
divTag.setAttribute('id', json[i].name);
var newAddedDiv = $('<div>').appendTo("#splitter");
newAddedDiv.html('fooooo');
}
}
In the success of ajax function,I have implemented like
success: function (json) {
for (var i = 0; i < json.length; i++) {
var j = i+1;
var div = document.createElement('div');
$('<div id = ' + json[i].prj '>').appendTo("#splitter");
----------------code for loading grid with different datasource--------------
}
$("#splitter").kendoSplitter({
orientation: "horizontal"
});
**code for loading grid with different datasource**
In the datasource read I gave like
transport: {
//passing values to the controller to display grid with different dataSource
read: {
url: function (options) {
return kendo.format("/Project/Display?selectedId=" + j + "");
}
}
}

Resources