I am passing an array variable to the controller.
Array from ajax call contains data but after calling the controller it shows count=0.
var url = '#Url.Action("UserRoleCompany_AddUserAccess", "UserRoleCompany")';
$.ajax({
url: url,
data: { userIDs: userIDs, Organisation: Organisation, RoleName: RoleName, userIDsLength: userIDsLength, UserStatus: UserStatus },
cache: false,
type: "POST",
success: function (data) {
location.reload(true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
Controller code below,
public ActionResult UserRoleCompany_AddUserAccess(List<int> userIDs, string Organisation, string RoleName, int userIDsLength,int UserStatus)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
objLMTDAL.UserRoleCompany_AddUserAccess(Organisation, RoleName, userIDsLength, UserStatus);
return RedirectToAction("Index");
}
And below are a screenshot for reference,
You can not pass an array as a parameter in ajax,you can either convert userIDs to a json string or combine them as a string,then pass to the controller side.
More details information can be found at Why the array will not send through the ajax call?
#lucumt
I have tried the same thing with table - selecting the multiple rows from the table and send it to the controller and it is working fine.
Please check below and let me know.
var url = '#Url.Action("UserRoleCompany_UpdateUserAccess", "UserRoleCompany")';
$.ajax({
url: url,
data: { Ids: checkedIds, newUserStatus: UserStatus },
cache: false,
type: "POST",
success: function (data) {
location.reload(true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
Controller
public ActionResult UserRoleCompany_UpdateUserAccess(List<int> Ids, int newUserStatus)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
string userRoleIds = String.Join(",", Ids);
objLMTDAL.UserRoleCompany_UpdateUserAccess(userRoleIds, newUserStatus);
return RedirectToAction("Index");
//return RedirectToAction("Index", "UserRoleCompany");
}
You can check the live scenario below in screenshots,
Related
I am getting this strange behavior in jQuery when working with mvc application.
Below is MVC view in which I have implemented Text change event,
#Html.TextBoxFor(m => m.UserId, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.UserId, "", new { #class = "text-danger" })
$("#UserId").change(function () {
var UserId = $(this).val();
//$("#txtName").val(emailId);
$.ajax({
url: 'GetValidUserName',
type: 'POST',
data: JSON.stringify({ UserId: UserId }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
if (!$.trim(data)) {
alert("User does not exist in system. Please enter valid User Id.");
$(':input[type="submit"]').prop('disabled', true);
}
else {
$("#UserId").val(data);
$("#UserId").focus();
$(':input[type="submit"]').prop('disabled', false);
}
}
});
});
While debugging application when I load Index view directly first time , jQuery function gets called and invoke the controller action properly.http://localhost:51012/UserApplication/Index
But when I load the view again, jQuery function doesn't get called.
Controller code,
public JsonResult GetValidUserName(string userId)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
string UserID = "";
objLMT.UserList = objLMTDAL.GetAll_User("", 0, "6");
var AllUsersInDatabase = from p in objLMT.UserList
where p.UserId == userId
select new
{
Name = p.UserName,
Id = p.UserId,
};
foreach (var user in AllUsersInDatabase)
{
if (user.Name != null)
{
UserID = user.Id;
}
}
return Json(UserID, JsonRequestBehavior.AllowGet);
}
You have several issues with AJAX callback:
1) type: 'POST' option requires [HttpPost] attribute. If the attribute isn't present on the action method, use type: 'GET' instead.
2) You don't need JSON.stringify() to pass single parameter containing simple types (numeric and string values). A simple { userId: UserId } should be fine.
3) The controller action's parameter name must be exactly match with parameter name sent from AJAX callback.
Therefore, your AJAX callback should be follow example below:
$(function () {
$("#UserId").change(function () {
var UserId = $(this).val();
$.ajax({
url: '#Url.Action("GetValidUserName", "ControllerName")',
type: 'GET',
data: { userId: UserId },
dataType: 'json',
success: function (data) {
if (!$.trim(data)) {
alert("User does not exist in system. Please enter valid User Id.");
$(':input[type="submit"]').prop('disabled', true);
}
else {
$("#UserId").val(data);
$("#UserId").focus();
$(':input[type="submit"]').prop('disabled', false);
}
}
});
});
});
So we are pretty new to ASP.Net MVC
We have this method that runs when we click on a button in our view. We would like to send the date string to our controller. How can we achieve this?
$('#calendar').fullCalendar({
//weekends : false
dayClick: function(date) {
console.log(date.format());
}
})
This is our controller
[HttpPost]
public IActionResult Booking(string test)
{
var booking = new Booking();
//booking.Date = dateTime;
Console.WriteLine(test);
var viewModel = new BookingsideViewModel
{
Subjects = new[] {"Matematik", "Dansk", "Engelsk"},
Booking = booking
};
return View();
}
you can do it using ajax call,
$.ajax({
url: '#Url.Action("Booking")',
data: { 'test' : date },
type: "post",
cache: false,
success: function (response) {
console.log("success");
},
error: function (error) {
console.log(error.message);
}
});
you can also write url like this:
url:"/ControllerName/ActionName"
Im wondering is it possible to render a view from a json result, basically when the user clicks on a button in my view, i want to go and fetch data from my controller/model using json result, with this data i want to open a view with the new data, is this possible?
AJax Call
$.ajax({
type: 'POST',
url: '#Url.Action("GetAdminSubmissions", "Inspections")',
contentType: "application/json; charset=utf-8",
datatype: JSON,
data: { 'selectedDepartment': deparment, 'searchDate': selectedDate },
success: function (result) {
// on success open view with new updated model
},
error: function (result) {
alert(result);
}
});
}
Controller
public JsonResult GetAdminSubmissions(string selectedDepartment, string searchDate)
{
var result = new List<Checks_Records>();
if (searchDate != null)
{
var enUkCultureInfo = new CultureInfo("en-GB");
var userSelectedDate = DateTime.Today.Date.AddHours(7);
DateTime parsedDate;
if (DateTime.TryParseExact(searchDate, "dd-MMMM-yyyy", enUkCultureInfo, DateTimeStyles.None, out parsedDate))
{
userSelectedDate = parsedDate.AddHours(7);
result = Model.GetListofChecks_Records(userSelectedDate, selectedDepartment);
var json = new JavaScriptSerializer().Serialize(result);
return Json(json, JsonRequestBehavior.AllowGet);
}
}
return error;
}
Here is an AJAX call to the controller:
$.ajax({
type: "GET",
url: '#Url.Action("getChat", "Chat")',
success: function (data) {
alert(data);
$("#data").html(data);
},
error:{
}
});
In the controller code, I have a database query which returns multiple rows.
I want to return that variable back to JSON and print each row separately in AJAX and write that data in HTML.
Here is my Controller code
public ActionResult getChat()
{
var p = (from v in DB.chats where v.chatuserID == id select new { v.status, v.message }).ToList();
return Content(p.ToString());
}
The query is returning data. I am attaching an image that shows the variables content.
public JsonResult getChat()
{
var p = (from v in DB.chats
where v.chatuserID == id select new { v.status,
v.message
}).ToList();
return json(p,JsonRequestBehavior.AllowGet);
}
Now you can loop through the list in you ajax success callback function : here is stuff.
$.ajax({
type: "GET",
url: '#Url.Action("getChat", "Chat")',
success: function (data) {
$.each(data,function(){
console.log("Status "+ data.status +" "+"Message"+ data.message);
});
},
error:{
}
});
How do I retrieve the ID from the following model, after the following JQuery/Ajax posts to it:
JQuery:
$.ajax({
type: 'POST',
url: '/api/searchapi/Post',
contentType: 'application/json; charset=utf-8',
data: toSend,
}).done(function (msg) {
alert( "Data Saved: " + msg );
});
Controller:
// POST api/searchapi
public Void Post(Booking booking)
{
if (ModelState.IsValid)
{
tblCustomerBooking cust = new tblCustomerBooking();
cust.customer_email = booking.Email;
cust.customer_name = booking.Name;
cust.customer_tel = booking.Tel;
bc.tblCustomerBookings.Add(cust);
bc.SaveChanges();
long ID = cust.customer_id;
Return ID; <-- what do I enter here?
}
Return "Error"; <-- and here?
}
How can I get the ID back into the jQuery script, and if the model isn't valid, how do I return an error to the jQuery?
Thanks for any help,
Mark
You could return a JsonResult
[HttpPost]
public ActionResult Post(Booking booking)
{
if (ModelState.IsValid)
{
tblCustomerBooking cust = new tblCustomerBooking();
cust.customer_email = booking.Email;
cust.customer_name = booking.Name;
cust.customer_tel = booking.Tel;
bc.tblCustomerBookings.Add(cust);
bc.SaveChanges();
return Json(new { id = cust.customer_id });
}
return HttpNotFound();
}
and then on the client simply:
$.ajax({
type: 'POST',
url: '/api/searchapi/Post',
contentType: 'application/json; charset=utf-8',
data: toSend,
}).done(function (msg) {
alert('Customer id: ' + msg.id);
}).error(function(){
// do something if the request failed
});
One way to do it is like this:
In your controller:
public Void Post(Booking booking)
{
//if valid
return Json(new {Success = true, Id = 5}); //5 as an example
// if there's an error
return Json(new {Success = false, Message = "your error message"}); //5 as an example
}
In your ajax post:
$.ajax({
type: 'POST',
url: '/api/searchapi/Post',
contentType: 'application/json; charset=utf-8',
data: toSend,
success: function(result) {
if (result.Success) {
alert(result.Id);
}
else {
alert(result.Message);
}
}
});
returning void isn't a good idea, use JsonResult
Because you are using JavaScript, I recommend using JSON.
return this.Json(new { customerId = cust.customer_id});
In order to receive a return value, the controller method must return something other than void.
Does your controller compile? Your post method has a void return type, so it should fail compilation when it sees the return ID and return "Error" commands