MVC DropDownList selection changed not firing Ajax - javascript

I am new to mvc and have been doing lots of looking, but I can't figure out why this isn't working.
I have the following View code:
$(function() {
$("#ddlNumberOfRecords").change(function() {
var numberOfRecords = $("#ddlNumberOfRecords").val();
$.ajax({
type: "POST",
url: '#Url.Action("NumberOfRecordsChanged")',
data: { numberOfRecords: numberOfRecords },
success: function(returndata) {
if (!returndata.ok) {
window.alert(' error : ' + returndata.message);
} else {
$('#Grid').html(returndata);
}
}
});
});
});
#Html.DropDownList("ddlNumberOfRecords", Model.NumberOfRecordsSelectList)
Can someone tell me what is wrong with that? Also, is there a way to debug that javascript? I put breakpoints on there, but they never load.
EDIT: This is my Action. There is no real content yet because I am just trying to get it to work at this point. But I have a breakpoint and it never gets hit.
[HttpPost]
public ActionResult NumberOfRecordsChanged(int numberOfRecords)
{
return null;
}

With everything you shown the code works 100%. I made a mock up to prove just that.
Controller
public ActionResult Index()
{
ViewModel model = new ViewModel
{
NumberOfRecordsSelectList = new List<SelectListItem>
{
new SelectListItem
{
Selected = false,
Text = "one",
Value = "1",
},
new SelectListItem
{
Selected = false,
Text = "two",
Value = "2",
},
}
};
return View(model);
}
[HttpPost]
public ActionResult NumberOfRecordsChanged(int numberOfRecords)
{
return null;
}
View
#model MvcApplication1.Models.ViewModel
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#ddlNumberOfRecords").change(function() {
var numberOfRecords = $("#ddlNumberOfRecords").val();
$.ajax({
type: "POST",
url: '#Url.Action("NumberOfRecordsChanged")',
data: { numberOfRecords: numberOfRecords },
success: function (returndata) {
//No return data proviced
//if (!returndata.ok) {
// window.alert(' error : ' + returndata.message);
//} else {
// $('#Grid').html(returndata);
//}
}
});
});
});
</script>
#Html.DropDownList("ddlNumberOfRecords", Model.NumberOfRecordsSelectList)
If you are getting another error than please share how you are creating your list items, what the error is, and any other details relevant to the problem. Thanks.

It seems you're trying to pass over the number of items in the dropdown but are in fact sending over the selected item's value.
If so, this...
var numberOfRecords = $("#ddlNumberOfRecords").val();
Should be this...
var numberOfRecords = $("#ddlNumberOfRecords option").size();

Related

Autocomplete in C# using typeahead not working

My JS function
<script type="text/javascript">
$(function () {
$("#pName").autocomplete({
source: '#Url.Action("GetExistingProducts")'
});
});
</script>
ID #pName is the id of the textbox which is in a Modal.
My GetExistingProducts function in the controller
public IEnumerable<string> GetExistingProducts()
{
return _traceProjectService.GetAllProducts();
}
This makes a call to GetAllProducts() in my service
public IEnumerable<string> GetAllProducts()
{
var productList = myContext.Projects.Select(x =>x.ProductName).ToList();
return productList;
}
Issue:
My JS function is not showing the existing Products when I start typing in my textbox.
References:
http://jqueryui.com/autocomplete/
Would appreciate if some could tell me what I am doing wrong. Thanks.
Try this:
<script src="~/Scripts/bootstrap3-typeahead.js"></script>
<script>
$.ajax({
url: '#Url.Action("GetExistingProducts", "Admin")',
type: "GET"
}).done(function(dt) {
var res = dt.split(",");
$(".pText").typeahead({
source: res,
showHintOnFocus: "all",
fitToElement: true
});
});
$.ajax({
url: '#Url.Action("GetExistingVersions", "Admin")',
type: "GET"
}).done(function(dt) {
var res = dt.split(",");
$(".vText").typeahead({
source: res,
showHintOnFocus: "all",
fitToElement: true
});
});
</script>
On controller side
public string GetExistingProducts()
{
var x = yourservice.function().toList();
string a = string.Empty;
foreach (var item in x)
{
a += item + ",";
}
return a;
}

ASP.NET MVC call Controller Action with parameter from javascript function

I have web application in ASP.NET MVC C#. I want to call Controller Action method with parameters from javascript but I get always null for parameters.
In .js I have:
$.ajax({
cache: false,
url: this.saveUrl,
type: 'post',
success: this.nextStep,
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
nextStep: function (response) {
if (response.error) {
if ((typeof response.message) == 'string') {
alert(response.message);
} else {
alert(response.message.join("\n"));
}
return false;
}
if (response.redirect) {
ConfirmOrder.isSuccess = true;
location.href = response.redirect;
return;
}
if (response.success) {
ConfirmOrder.isSuccess = true;
window.location = ConfirmOrder.successUrl;
//window.location.href = #Url.Action("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" });
//window.location.href = '#Html.GetUrl("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" })';
}
Checkout.setStepResponse(response);
}
in RouteProvider.cs I have:
routes.MapLocalizedRoute("CheckoutCompleted",
"checkout/completed/{orderId}/{customerComment}/{customerDate}",
new { controller = "Checkout", action = "Completed", orderId = UrlParameter.Optional, customerComment = UrlParameter.Optional, customerDate = UrlParameter.Optional },
new { orderId = #"\d+", customerComment = #"\w+", customerDate = #"\w+" },
new[] { "Nop.Web.Controllers" });
And finaly in Controller I have:
public virtual ActionResult Completed(int? orderId, string customerComment, string customerDate)
{
//some code here
}
I always get parameters value null and I don't know why. I try to call this Action with parameters on several diferent way like I saw on this forum but no success.
Did you add httpPost wrapper to your controller ?
[HttpPost]
public virtual ActionResult Completed(MyClass MyClassObj )
{
//some code here
}
in your Ajax code u didn't mention your Data type And Data try This Ajax
function Save () {
try {
var req = {
DeliveryCode: value,
}
$.ajax({
url: URL,
type: 'POST',
data: req,
dataType: "json",
async: true,
success: function (result) {
resetLoadWaiting()
},
error: function (e) {
}
});
}
catch (e) {
}
}
Mistake was in url string. Correct one is
ConfirmOrder.successUrl = "http://localhost:8079/checkout/completed/?customerComment=eee&customerEstimateShippingDate=2017-11-14"
I found this solution in this answer: Routing with Multiple Parameters using ASP.NET MVC
I dont need to update RouteProvider with new parameters. It is enough to put in in Controller Action method. Other things happen automatically.

How to check the checkbox in kendo treeview using the values passed from the controller?

The code below generates the nodes for kendo treeview from the controller
var datasource = new kendo.data.HierarchicalDataSource({
transport: {
read: function(options) {
var id = options.data.ModuleId;
$.ajax({
url: '/MapModuleTask/LoadTreeView',
dataType: "json",
data: {
id: id
},
success: function(result) {
options.success(result);
},
error: function(result) {
options.error(result);
}
});
}
},
schema: {
model: {
id: "ModuleId",
hasChildren: "hasChildren"
}
}
});
I want to populate/check these check boxes using the ID's I get from my controller
this is my controller action method
public int?[] LoadModulesByFranchisorId(string FranchisorId)
{
int?[] modules;
var modulesList = (from a in db.MapModuleFranchisors where a.FranchsiorId == FranchisorId && a.ModuleFlag == 1 select a.ModuleId).AsEnumerable().ToArray();
modules = modulesList;
return modules;
}
The Ids' I get from the action method above are Ids' of the check-box
Thank you in advance... :)
Controller Action method should be something like this(i.e returning a Json response).
public JsonResult getModulesByFranchisorID(string FranchisorId)
{
var FranchisorModules = (from a in db.MapModuleFranchisors
where a.FranchsiorId == FranchisorId && a.ModuleFlag == 1
select new
{
a.ModuleId,
}).AsEnumerable();
return Json(FranchisorModules, JsonRequestBehavior.AllowGet);
}
I called for the following method inside the ajax 'success' statement. This checked the check boxes from the values returned from the controller.
function checkNodes() {
treeView = $("#treeview").data("kendoTreeView");
var tpNodes = treeView.dataSource.view();
var FranchisorId = '#Model.FranchisorId';
$.ajax({
type: "POST",
url: "/MapModuleTask/getModulesByFranchisorID",
data: {
FranchisorId: FranchisorId
},
success: function(data) {
var dataLength = data.length;
console.log(dataLength);
console.log(tpNodes);
for (var i = 0; i < dataLength; i++) {
for (j = 0; j < tpNodes.length; j++) {
debugger;
if (tpNodes[j].ModuleId == data[i].ModuleId) {
debugger;
var selectitem = treeView.findByUid(tpNodes[j].uid);
selectitem.addClass('k-state-selected');
treeView.select().find(".k-checkbox input").attr("checked", "true");
}
}
}
}
});
}
There might be better or more efficient way, this was working for me. Feel free to correct me.
Thank you.

Problems updating database with Jquery.Ajax

I am working on a website and would like to be able to update a field on a database table when a div is clicked. I found some example code right here on stack but for some reason it won't work, even though it was accepted. I am using C# ASP.NET MVC Razor.
My JavaScript function is as follows:
function toggleContent(id, instID) {
var doc = document.getElementsByClassName("messageContent")[id];
$(doc).slideToggle();
$.ajax({
type: 'POST',
url: "#Url.Content('/Messages/MarkSeen/')",
data: {
instanceID : instID
},
dataType: 'json'
});
}
And my JsonResult is as follows:
[HttpPost]
public JsonResult MarkSeen(int instanceID)
{
var markSeen = db.MessageInstances.First(mi => mi.MessageInstanceId == instanceID);
if (markSeen.RegisteredPerson.PersonId == CurrentUser.PersonId)
{
markSeen.Seen = true;
db.SaveChanges();
return Json(true);
}
return Json(false);
}
I'm not sure where your code fails, so I posted complete working code
If you are using the ApiController, please try the following updates to make your code works:
1. add route to WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
2. javascript
$.ajax({
type: "POST",
url: "#Url.Content("/api/lab/MarkSeen")",
data: { "instanceID": instID },
dataType: 'json',
success: function (data) { alert(data)},
error: function () { alert('error'); }
});
3. Add model to match the json from ajax request:
public class labModel
{
public int instanceID { get; set; }
}
4. Controller:
[System.Web.Mvc.HttpPost]
public JsonResult<bool> MarkSeen(labModel data)
{
return Json(true);
}

How can I access a JavaScript array in my MVC controller?

I’ve created an array inside a javascript. Now I want to use the array controller. Currently I’m using FormCollection to access data from the form. Is there a way to access my javascript array in FormCollection or as a parameter in the Html.BeginForm()?
I’ve tried doing a JSON post using some examples I found on the forum but the array was null in the controller. Can you please help with the best approach to accessing my javascript array in the controller?
<script type="text/javascript">
var $checkboxes = $('input[type="checkbox"]');
$(document).ready(function () {
$('#saveBtn').click(function () {
var checkList = new Array();
$.each($checkboxes, function () {
if ($(this).is(':checked')) {
checkList.push('checked');
}
else
checkList.push('unchecked');
});
alert(checkList);
});
});
</script>
UPDATE 1
$(document).ready(function () {
$('#saveBtn').click(function () {
var options= [];
$.each($checkboxes, function () {
if ($(this).is(':checked')) {
var item={ "UserChoice" : "checked", "OptionID": "YouCanSetIDHere"};
}
else
{
var item={ "UserChoice" : "unchecked", "OptionID": "YouCanSetIDHere"};
}
options.push(item);
}
$.ajax({ type: "POST", url: '#Url.Action("Edit","Attendance")',
contentType: "application/json",
data: JSON.stringify(options)
}).done(function (html) {
//do something with the response.
});
});
});
You can create items which is similar to your viewmodel and push that to your array and post it using jQuery post. In your controller action, you can use a collection of your viewmodel to accept it. MVC model binding will take care of the rest.
Assume you have a ViewModel like this
public class UserOptionVM
{
public string OptionID{ set;get;}
public string UserChoice { set;get;}
}
And in your Action method, you accept a collection of this
[HttpPost]
public ActionResult Save(List<UserOptionVM> model)
{
// loop through collection and read and save
}
Now change your Js file to send something which match with our viewmodel.
var options= [];
$.each($checkboxes, function () {
if ($(this).is(':checked')) {
var item={ "UserChoice" : "checked", "OptionID": "YouCanSetIDHere"};
}
else
{
var item={ "UserChoice" : "unchecked", "OptionID": "YouCanSetIDHere"};
}
options.push(item);
});
$.ajax({ type: "POST",
url: "#Url.Action("Save","User")",
contentType: "application/json",
data: JSON.stringify(options)
}).done(function (html) {
//do something with the response.
});

Categories

Resources