jQuery function not getting called in mvc text-changed event - asp.net

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

Related

Ajax call not passing arrays to controller action

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,

Send string from View to Controller ASP.Net mvc

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"

Render View with Json Result

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

MVC3 JSON Return to Edit Page

So I have some javascript code that sends data to my controller:
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$("#newGrade").click(function () {
var newGradeName = $("#newGradeName").val();
var newGradeValue = $("#newGradeValue").val();
var vSchoolID = $("#SchoolID").val();
if (newGradeName != null && newGradeValue != null) {
$.ajax({
url: '#Url.Action("NewGrade", "School")',
data: { gradeName: newGradeName, gradeValue: newGradeValue, schoolID: vSchoolID },
type: 'POST',
traditional: true,
success: function (data) {
if (data.status)
window.location = data.route;
},
error: function () {
return false;
}
});
}
});
});
</script>
Controller:
public ActionResult NewGrade(String gradeName, Int32 gradeValue, Guid schoolID)
{
School school = schoolRepository.GetByID(schoolID);
school.Grades.Add(
new Grade
{
GradeID = Guid.NewGuid(),
Name = gradeName,
NumericalValue = gradeValue
});
schoolRepository.Update(school);
schoolRepository.Save();
if (Request.IsAjaxRequest())
{
var json = new { status = true, route = Url.RouteUrl(new { action = "Edit", id = schoolID }) };
return Json(json, JsonRequestBehavior.AllowGet);
}
return View();
}
My issue now is I want to return to my Edit page (possibly refreshing the page, but not the data, or just refresh the entire page), but my Edit page takes an ID (schoolID). Shown here when pressing the button to get to the Edit page:
<i class="icon-pencil"></i> Edit
Try window.location.href and see what happens.
success: function(data) {
if (data.status)
window.location.href = data.route;
},
This should work fine assuming you are getting a JSON reponse from your action method like
{"status":"true","route":"/School/Edit/1"}
where 1 is the ID of new record.

How to handle $.ajax

I want to send JSON data to an action that will update some data. I then want to either redirect to another action or send back an error message to $.ajax.
Is possible with $.ajax otherwise how can I?
Becase following code does not redirect.
[code]
[HttpPost]
public ActionResult Save(RecipeViewModel postdata)
{
Recipe recipe = postdata.GetRecipe(_user.UserID);
int recipeid = _service.AddRecipe(recipe, null, true);
foreach (Ingredient ing in recipe.Ingredients)
{
ing.RecipeID = recipeid;
_service.AddIngredient(ing, null, false);
}
if (!postdata.Comment.IsEmpty())
{
Comment comment = new Comment();
comment.fldComment = postdata.Comment;
comment.RecipeID = recipeid;
comment.UserID = _user.UserID;
comment.EnteredByName = _user.Names;
comment.EnteredOn = DateTime.Now.ToString();
_service.AddComment(comment, null, false);
}
_service.SubmitChanges();
return RedirectToAction("View", "Recipe", new { id = recipeid });
}
u<script type="text/javascript">
$("#Save").click(function () {
var ingredients = $("#ingredients tr.ingredientdata").map(function (element, index) {
return {
ingredientName: $("td.ingredient", this).text(),
units: $("td.units", this).text(),
measure: $("td.measure", this).text()
};
}).toArray();
var json = {
RecipeTitle: $("#recipetitle").val(),
CategoryID: $("#category").val(),
PrepTime: $("#prepTime").val(),
PrepTimePeriod: $("#lstPrepTime").val(),
CookTime: $("#cookTime").val(),
CookTimePeriod: $("#lstCookTime").val(),
Rating: $("#rating").val(),
Method: $("#method").val(),
Comment: $("#comment").val(),
AccessLevel: $("#accessLevel").val(),
Ingredients: ingredients
};
$.ajax({
url: "/Recipe/Save",
type: "POST",
dataType: 'json',
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
success: function () {
//alert("DONE!!");
}
});
});
[/code]
Malcolm
You need to send back the Url and redirect it from the client script.
success: function (urlData) {
window.location.href = urlData ;
return false;
}
or you may show an error message based on the response received.

Resources