In my MVC web application I have a button on the LyncUser Create view that needs to get the value of 'AddressBookNBo' and pass this to the findEmpSurname in my Staff controller. This action then uses the AddressBookNo to retrieve the Surname value from the Staff model. The Surname value is then used to automaticatically populate the Surname value on the LyncUser create view.
When I debug the app and put a stop on the controller action I can see that AddressBookNo is null. Can you advise what I am doing wrong here please.
findEmpSurname action in Staff...
[HttpGet]
public JsonResult FindEmpSurname(int? AddressBookNo)
{
var staffDB = new StaffEntities();
var surnames = staffDB.Staff.AsQueryable();
if (AddressBookNo != null)
{
surnames = surnames.Where(p => p.AddressBookNo == AddressBookNo);
}
return Json(surnames.Select(p => new { Surname = p.Surname }), JsonRequestBehavior.AllowGet);
}
Telerik Kendo UI MVC button that calls the PopTextBox javascript when clicked.
#(Html.Kendo().Button()
.Name("findEmpSurname")
.Content("Lookup Surname")
.HtmlAttributes(new { type = "button" })
.Events(ev => ev.Click("PopTextBox"))
)
PopTextBox javascript that gets the value of AddressBookNo, passed this to the controller, and uses the returned value to set the Surname value.
function PopTextBox()
{
var data = { AddressBookNo: $("AddressBookNo")[0].value };
$.ajax({
url: '#Url.Action("FindEmpSurname","Staff")',
type: 'GET',
dataType: 'json',
data: data,
cache: false,
success: function (result) {
var surnameTextbox = document.getElementById('Surname');
surnameTextbox.value = result;
}
})
}
Related
I debugged the JS and Ajax code with console.log. I can see that what I entered into the textbox, is displayed in the console. However, when these values are supposed to send to the controller, they are empty or null when I hover over the tbl_stuff List. Not sure where I am making a mistake.
Here is the JS:
$("body").on("click", "#btnSave", function () {
var table = $("table tbody");
var array= new Array();
table.find('tr').each(function (i) {
var $tds = $(this).find('td'),
Amount = $(this).find('.val').val();
valuestoupdate = { Amount: amount };
array.push(valuestoupdate);
});
$.ajax({
type: "POST",
url: "#Url.Action("StuffAction","Home")",
data: JSON.stringify(array),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) saved.");
}
});
Here is the controller action:
public JsonResult StuffAction(List<tbl_Stuff> stuffs)
{
int getID = (int)TempData["id"];
TempData.Keep();
var GetData = _context.tbl_Detail.Where(x => x.detId == getID).FirstOrDefault();
if (GetData != null)
{
foreach (tbl_Stuff moreThings in stuffs)
{
tbl_Stuff stuff = new tbl_Stuff();
stuff.Amount = moreThings.Amount;
_context.tbl_Stuff.Add(stuff);
}
}
int insertedRecords = _context.SaveChanges();
return Json(insertedRecords);
}
I get an error saying that moreThings.Amount is empty. But during debugging, the JS code gets the value entered into the textbox.
The .Net routing can't match the request
change the action signature to public JsonResult StuffAction(List< string > stuffs)
or in your ajax call change the array to an array of objects matching the properties of tbl_Stuff
I am trying to fill a dropdown using ajax and a controller action, but nothing seems to be happening when I click the button that triggers the action:
Ajax:
$.ajax({
url: '#Url.Action("GetBranch", "Report")',
type: "GET",
success: function (result) {
$("#dropdown2").append('<option value=' + result.BranchId + '>' + result.BranchName + '</option>');
}
});
Controller Action:
public ActionResult GetBranch()
{
var branch = new Branch();
var branchId = branch.BranchId;
var branchName = branch.BranchName;
return Json(new[]
{
new {Id = branchId, Value = branchName}
}, JsonRequestBehavior.AllowGet);
}
This is a practice I am not too familiar with so there could be something obvious missing. None of the answers here have been able to help me because I am trying to bind to an existing <select>; not a #DropdownListFor
It seems that the controller action is not getting hit with the ajax call, so nothing is getting returned.
Thanks for your help!
public JsonResult GetBranch()
{
var branch = new Branch();
var branchs = new List<Branch>();
var branchId = "Branch01"; //If only your branch id datatype is string
branch.branchId = branchId;
var branchName = "Name of Branch";//Name you want to give for your branch
branch.branchName = branchName;
branchs.Add(branch);
return Json(branchs.Select(t => new {Text = t.branchName, Value = t.branchId}), JsonRequestBehavior.AllowGet);
}
I asked a question to fill in the model data on the client, into arrays.
Add items to JSON objects
Now my problem is how to post it to the controller. I have tried this:
public ActionResult ItemRequest (Model1 model)
{
////
}
but it never gets there.
I'm trying with an AJAX request to send it:
function sendRequest() {
jsonData.items = itemArray;
$.ajax({
url: '#Url.Action("ItemRequest")',
type: 'POST',
data: JSON.stringify(jsonData),
///// and so on
}
But the action result is never invoked. I can drop the 'JSON.stringify' and it makes no difference. Any ideas on how to post this object to the controller?
If I make a psuedo model in JS it works fine, but I don't want to have to make this model, I'd rather use the model passed to the page.
function itemModel () {
var self = this;
this.itemNumber = $("#itemNumberId").val();
/// etc.
self.items = [];
}
function itemsModel () {
var self = this;
this.itemNumber = $("#itemNumberId").val();
/// etc
}
then
var itemCount = 0;
function addItem() {
var newItem = new itemModel();
newItem.items[itemCount] = newItem;
/// etc
}
This works fine.
I send the array itemModel the same way with a JSON.stringify directly into the controller method
public ActionResult ItemRequest(ItemModel model)
We are using this to send Data to API controller Methods on our internal test sides:
It's probably not the prettiest solution, but it can be used on any page.
What data should be sent:
$("#btnSend").click(function () {call("controller/method", {ParamName: $("#field").val()}); });
To send the data to a controller:
$(document).ready(function () {
var call = function (method, requestData, resultHandler) {
var url = method.substring(0, 1) == "/api/" + method;
$.ajax({
url: url,
dataType: 'json',
data: JSON.stringify(requestData),
type: 'POST',
contentType: 'application/json',
success: function (data) {
var isSuccess = data.Status == "success";
$("#jsonResponse").val(FormatJSON(data));
if (isSuccess && jQuery.isFunction(resultHandler)) {
resultHandler(data);
}
}
});
};
in view somewhere I need to assign value from action which returns json object I would like to assign like below:
<script type="text/javascript">
var jsonFromAction = #Html.Action("GetMenuJson", "Test");
</script>
My Controller Action Code is below:
public ActionResult GetMenuJson(int? subCategoryId)
{
_lCatService = new LeftCategoryService();
List<FlatObject> flatObjects = _lCatService.GetCategory(UIUtility.Uitlity.CurrentLanguageCode);
return Json(GetList(flatObjects, 0), JsonRequestBehavior.AllowGet);
}
make a ajax call :
$.ajax({
type: "Get",
url: 'GetMenuJson',
data: "Test",
success: function (result) {
var jsonFromAction = result;
}
});
and your api's return type should be Json (JsonResult), so that it can return the Json
When I ran below code for bttn click event it doesn't return a data for success method.
But it goes for controller method and return false (boolean value) as a out put.I need to pick that boolean value from javascript code.
Why it doesn't work ?
Javascript code is as below:
$('#btnClockInTime').off('click').on('click', function () {
var isClockOutTimeCompleted = true;
$.ajax({
url: "/Employees/IsClockOutTimeCompleted",
type: "GET",
dataType: "json",
cache: false,
data: { employeeId: employeeId },
success: function (data) {
if (!data) {
isClockOutTimeCompleted = data;
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
return false;
});
Controller Action Method is as below:
[HttpGet]
public JsonResult IsClockOutTimeCompleted(Guid employeeId)
{
var clockingDate = Convert.ToDateTime(DateTime.Today);
var isClockOutTimeCompleted = Repository.IsClockOutTimeCompleted(employeeId, clockingDate);
return Json(isClockOutTimeCompleted, JsonRequestBehavior.AllowGet);
}
Repository code is as below:
public bool IsClockOutTimeCompleted(Guid employeeId, DateTime clockingDate)
{
var clockOutTime = (from c in Catalog.EmployeeClockInOutTimes
where (c.Employee.Id == employeeId && c.Created == clockingDate && c.ClockOut == null)
select c).FirstOrDefault();
return clockOutTime == null;
}
UPDATE :
Response is as below :
UPDATE 2 :
Screen 1 :
Screen 2 :
Screen 3 :
As shown above images my debug doesn't come into success method.
After 2nd screen (when debug at error) it goes to controller and brings data.
3rd screen shows a status after returning from controller.Any idea ?
I would have thought that if you're return value is just false as a string then that will become your data value and as a result:
if (!data) { // won't fire }
As Darin says, if you wrap up your response Json inside an object and then use that to assign to your isClockOutTimeCompleted variable.
I wouldn't have thought you'd want to perform a boolean evaluation of your return value if it's a true/false return type, wouldn't you just want to assign it to isClockOutTimeCompleted either way?
if ur posting data to a controller method always use
'type':'POST' in ur ajax call &
change the [HTTPget] attribute from ur controller method to [httpPost]
below is my sample code which works fine
$.ajax({
url: 'Home/temp',
type: 'POST',
dataType: "json",
data: {'name':'surya'},
success: function (data) {
console.log(data);
//here i'm getting the data which i have passed
},
error: function () {
console.log("inside error")
}
});
and my controller code
[HttpPost]
public JsonResult temp(string name) {
return Json(name);
}
i'm getting back the data which i have passed in to the controller method via my jquery ajax..
may be u ought to change ur 'IsClockOutTimeCompleted' method where u are performing linq queries.just validate ur linq queries once..and also employeeId which ur passing into the controller is of type integer then instead of GUID as a parameter why dont u change the parameter type as int and see..
Regards