im trying to get the value each time a client selects a option from my Dropdown list to send it back to controller where i use the value on creating a file and then refreshing the page but im unable to do so
This is my Dropdownlist:
<select id="sel0">
<option value="">Todos</option>
#foreach (var item in Model.Select(l => l.Fecha).Distinct())
{
<option value="#lines">#lines</option>
}
</select>
This is my Ajax Call:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
});
$("form").submit(function () {
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
and this is my Controller its named 'HomePosController':
public ActionResult MethodName(string Selected)
{
var db = new ArponClientPosContext();
String value = Selected;
var json4 = JsonConvert.SerializeObject(Selected);
System.IO.File.WriteAllText(#"C:\inetpub\wwwroot\potzolcalli.brain.arpon.com\valorselected.txt", json4);
return View("~/Views/HomePos/Index.cshtml", db.Pos.ToList());
}
But whenever y select a option of my dropdown nothing happens, the page its not refreshed nor the file is created what am i doing wrong?
If you want it to be on dropdown change then you have to send ajax call in change event :
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePos")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
and you have to not write complete Controller class name, you have to skip the Controller postfix, it is convention which is followed by Url helpers in mvc, that way your url generated will be wrong and ajax call will fail.
whenever y select a option of my dropdown nothing happens
Well, this happens:
dataTable.columns('.fechas').search(this.value).draw();
But that doesn't invoke the AJAX request. It doesn't do much of anything, really.
how can i trigger the ajax ? i want it to trigger after a value is changed in the dropdown list
In that case you want to do that on the select element's change event. Currently you perform the AJAX request here:
$("form").submit(function () {
// AJAX
});
That is, you perform the request in the form's submit event. Just add it to the drop down's change event instead:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
the page its not refreshed
Well, no. That won't happen in an AJAX request. Currently your success callback is empty, so nothing will happen on the page. Whatever you want to happen would need to be put in that callback.
Related
I am running Asp.Net Core 3.1 application where i have one left side menu in layout which i load through partial view.
To set menu link i used the anchor tag like below:
var allRouteData = new Dictionary<string, string>
{
{ "menuid", mID.ToString() },
{ "isCalledByMenu", "true" },
{ "where", "tab" }
};
<a class="#clas" data-ajax="true" data-ajax-complete="RedirectToPage('#M.MenuUrl', '#M.MenuName',true)" data-ajax-mode="replace" data-ajax-update="#myTab" asp-action="GetSubMenu" asp-controller="Base" asp-all-route-data="#allRouteData">#M.MenuName</a>
So when page loads then HTML generate like below:
<a class="nav-link btn fuse-ripple-ready" data-ajax="true" data-ajax-complete="RedirectToPage('/OrgOverview/ProfessionalServices', 'Professional Services',true)" data-ajax-mode="replace" data-ajax-update="#myTab" href="/Base/GetSubMenu?menuid=9630&isCalledByMenu=true&where=tab">Professional Services</a>
Below is action method used :
public IActionResult GetSubMenu(int menuid, bool? isCalledByMenu, string where = null)
{
return ViewComponent("SubMenu", new { menuid = menuid, isCalledByMenu = isCalledByMenu, where = where });
}
In Layout page on the top i assigned the tag helper:
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
But when i click on the link it is not hitting this action method.
Update: When i click menu then first it hit the list inside javascript where i do some ajax call:
$('#myTab>li>a.nav-link.btn.fuse-ripple-ready').on("click", function (e) {
e.preventDefault();
var requestedPage = $(this).text();
SetCurrentPageNameSession(requestedPage, false);// ajax call to set some value.
return true;
});
In SetCurrentPageNameSession method i do ajax call to set the menu name in server side to some session before calling action method.
like below:
function SetCurrentPageNameSession(CurrentPage, IsBookMark) {
if (IsBookMark==undefined)
IsBookMark = false;
var url = baseUrl+"Manage/HighlightCurrentMenu/"
$.ajax({
type: "POST",
data: { CurrentPage: CurrentPage, IsBookMark: IsBookMark },
url: url,
dataType: "json",
async:false,
success: function (data) {
var res = data.d;
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
Then after it anchor tag call the action method.
Please suggest.
Maybe you could forget data-ajax, it also doesn't work on me and I can't find the answer about it. You could code as below and it also can request the GetSubMenu and continue to excute next logic.
<div id="myTab"></div>
<a class="nav-link btn fuse-ripple-ready"
href="#">Professional Services</a>
<script>
$('a.nav-link.btn.fuse-ripple-ready').on("click", function (e) {
//e.preventDefault();
$.ajax({
url: "/Base/GetSubMenu",
async: true,
type: "get",
datatype: "json",
data: #Json.Serialize(allRouteData),
success: function (result) {
$('#myTab').html(result)
}
});
//RedirectToPage('/OrgOverview/ProfessionalServices', 'Professional Services', true);
var requestedPage = $(this).text();
SetCurrentPageNameSession(requestedPage, false);// ajax call to set some value.
return true;
});
</script>
Comment or Remove e.preventDefault();
Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.
I found the solution for the above asked question:
The issue was when i click on menu link then i used to call first it's anchor click in javascript where i did e.preventDefault() and then used to do some ajax call to pass some value to set in session. Due to e.preventDefault() call after that it was not hitting the action method.
Since i had to pass other three data to server to set somewhere. To do that i set all three value in anchor tag data-link attribute separated with Pipe like below:
data-link="9630|true|tab|/OrgOverview/ProfessionalServices|Professional Services"
function SetCurrentPageNameSession(CurrentPage, IsBookMark, MenuID, IsCalledByMenu, Where, PageUrl, PageName) {
var url = baseUrl+"Manage/HighlightCurrentMenu/"
$.ajax({
type: "POST",
data: { CurrentPage: CurrentPage, IsBookMark: IsBookMark, menuID: MenuID, isCalledByMenu: IsCalledByMenu, where: Where},
url: url,
dataType: "json",
async:false,
success: function (data) {
var res = data.d;
if (PageUrl != undefined && PageUrl != '' && PageUrl != null)
RedirectToPage(PageUrl, PageName, true, false)
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Then in this ajax call success i am redirecting the page with passed page url.
But still i am wondering the same code how it was working in MVC and not in asp.net core.
That's it.
I have a controller that applies to an edit view in asp.net MVC. I have an actionlink that sends the row Id to the controller which then brings back the correct row to see in the associated view.
I then have a partial view below that. That also requires a parameter in order to bring associated data from another table.
I have a Jquery .post call that runs after the page is loaded. I can alert out and show the exact value I want to send to the controller.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").serialize();
alert(Uc);
$.post(url, {Id: Uc}, function (data) {
alert("what is Uc now? " + uc); //just for testing
});
})
I have also used it this way.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").val();
alert(Uc);
$.post(url, Uc, function (data) {
});
})
the alerts come up and show the value I want. However, when the .post call runs, it sends a null value. Here is my controller.
public ActionResult MmsAndNotes(string Id)
{
//Declare LogisticsVM for individual policy info
LogisticsMMS_NotesVM model;
if(uc == null)
{
return Content("uc is empty.");
}
int val = Convert.ToInt32(uc);
using (Db db = new Db())
{
LogisticsMMS_NotesDTO dto = db.LogisticsMMS.Find(val);
//confirm policy exists
if (dto == null)
{
return Content("This policy cannot be found." + val);
}
model = new LogisticsMMS_NotesVM(dto);
}
return PartialView(model);
}
It always returns as uc is empty. I repeat, when the alerts come up. I get the correct value to send to the controller. But once it sends, something happens and it converts to null. HELPPPPP.. please .. I'm losing my mind over this one.
I don't know why, but changing my $.post() call to an $.ajax({}) call solved the issue. As you can see above, I had the $.post call. Using this instead,
$.ajax({
type: "POST",
url: "/Home/MmsAndNotes",
dataType: 'text',
data: { Id: Uc }
});
Solved it. I thought Jquery's shortened calls worked the same way. They certainly might, but doing it this way was the only way it worked for me.
P.S. Thanks Tyler (above) for your comments.
this solution should be work :
$(document).ready(function () {
$.ajax({
url: '/Home/MmsAndNotes',
type: 'GET',
dataType: "html",
data: { uc : $("#Id").val() },
success: function (result) {
code here
}
});
})
You need to verify if $("#Id").val() is not empty
I am trying to update my database when a checkbox is checked or unchecked. I want it to update when the checkbox is clicked. This is what I have so far, but my controller is never being hit. what can I do to fix it? Ideally I want to pass in the new value of customer.IsDone and customer.Id to my controller but I don't know how to do this.
Checkbox in my view
<td>#Html.CheckBoxFor(m => customer.IsDone, new { onclick = "UpdateCustomer(IsDone)" })</td>
The function in my view
function UpdateCustomer(isDone) {
$.ajax({
type: 'POST',
url: #Url.Action("UpdateCustomer", "Home"),
data: { check: isDone },
success: success,
dataType: 'json'
});
}
this is my controller method
[HttpPost]
public ActionResult UpdateCustomer(bool check)
{
//code will be here to update the db
var customers = new CustomerGetAll();
var list = customers.Execute();
return View("Customers", list);
}
I see few issues in your code.
First of all, you are passing IsDone variable when calling the UpdateCustomer method. But where is isDone defined ?
Second, this line,
url: #Url.Action("UpdateCustomer", "Home"),
The Url.Action helper will output a string and your code will be like this when rendered in the browser
url: /Home/UpdateCustomer,
Now the browser's javascript framework usually thinks the second part after : as a js variable and if you have not defined it,it will throw a syntax error about using a not defined variable! But since we have \, you will get another "Invalid regular expression flags" syntax error!
You should wrap the result in quotes to avoid this problem.
The below code should work
#Html.CheckBoxFor(m =>customer.IsDone, new { onclick = "UpdateCustomer(this)" })
and the script
function UpdateCustomer(elem) {
var isDone = $(elem).is(':checked');
$.ajax({
type: 'POST',
url: "#Url.Action("UpdateCustomer", "Home")",
data: { check: isDone },
success: function(res) {
console.log(res);
},
dataType: 'json'
});
}
Also, If you want to update a specific customer record, you probably want to pass the customer Id as well when making the ajax call. You may keep that in html 5 data attribute on the checkbox markup and read that and use that as needed.
#Html.CheckBoxFor(m =>customer.IsDone, new { onclick = "UpdateCustomer(this)",
data_customerid = customer.Id })
This will render the checkbox with html5 data attribute for "data-customerid". All you have to now do is, read this value and send it via ajax
function UpdateCustomer(elem) {
var isDone = $(elem).is(':checked');
var cid = $(elem).data('customerid');
$.ajax({
type: 'POST',
url: '#Url.Action("UpdateCustomer", "Home")',
data: { check: isDone,customerId:cid },
success: function(res) {
console.log(res);
}
});
}
Make sure your server action method has a new parameter to accept the customer id we are sending from client side code
[HttpPost]
public ActionResult UpdateCustomer(bool check,int customerId)
{
// to do : Save and return something
}
I have something similar, and I think you can solve your problem...
My HTML
<td>
#{
bool avalia1 = false;
#Html.CheckBox("avalia1", avalia1, new { autocomplete = "off", data_on_text = "Sim", data_off_text = "Não" })
}
</td>
JS
var avalia1 = $("#avalia1").is(":checked");
var url = "/Telefonia/GravarAvaliacao";
$.ajax({
url: url,
datatype: "json",
data: { 'avalia1': avalia1,'idgravacao': idgravacao },
type: "POST",
success: function (data) {
}
});
}
ON CONTROLLER
public JsonResult GravarAvaliacao(bool avalia1, string idgravacao)
{
string _userId = User.Identity.GetUserId();
var avaliaData = new OperadorAvaliacaoData();
avaliaData.GravaAvaliacao(avalia1, idgravacao);
return Json(true, JsonRequestBehavior.AllowGet);
}
The only diference is your model checkbox, and the action trigger.
I am using ASP.NET MVC3 with EF Code First. I have not worked previously with jQuery. I would like to add autocomplete capability to a dropdownlist that is bound to my model. The dropdownlist stores the ID, and displays the value.
So, how do I wire up the jQuery UI auto complete widget to display the value as the user is typing but store the ID?
I will need multiple auto complete dropdowns in one view too.
I saw this plugin: http://harvesthq.github.com/chosen/ but I am not sure I want to add more "stuff" to my project. Is there a way to do this with jQuery UI?
Update
I just posted a sample project showcasing the jQueryUI autocomplete on a textbox at GitHub
https://github.com/alfalfastrange/jQueryAutocompleteSample
I use it with regular MVC TextBox like
#Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", #class = "ui-widget TextField_220" })
Here's a clip of my Ajax call
It initially checks its internal cached for the item being searched for, if not found it fires off the Ajax request to my controller action to retrieve matching records
$("#SearchField").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in entityCache) {
response(entityCache[term]);
return;
}
if (entitiesXhr != null) {
entitiesXhr.abort();
}
$.ajax({
url: actionUrl,
data: request,
type: "GET",
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "json",
success: function (data) {
entityCache[term] = term;
response($.map(data, function (item) {
return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode };
}));
}
});
},
minLength: 3,
select: function (event, result) {
var id = result.item.id;
var code = result.item.code;
getEntityXhr(id, code);
}
});
This isn't all the code but you should be able to see here how the cache is search, and then the Ajax call is made, and then what is done with the response. I have a select section so I can do something with the selected value
This is what I did FWIW.
$(document).ready(function () {
$('#CustomerByName').autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
},
});
},
select: function (event, ui) {
$('#CustomerID').val(ui.item.id);
},
minLength: 1
});
});
Works great!
I have seen this issue many times. You can see some of my code that works this out at cascading dropdown loses select items after post
also this link maybe helpful - http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx
I'm doing an app and I got a select where the user can choose different Teams. Each team contains a couple of patients. I save the chosen team with the data-bind selectedOptions and stores the option to an observable called 'selectedTeam'.
I'm receiving a list of patients by calling
self.searchPatients = function () {
$.getJSON("/api/API/GetPatients", function (data) {
ko.mapping.fromJS(data, {}, self.patients);
});
};
self.searchPatients();
Back at my APIController I got a method that asks the DB for patients. This calls takes different arguments, one of them being what team to search from.
My question is how to pass the observable 'selectedTeam' to my APIController, convert it to a string to pass it to the DB call.
thx
You can pass the data as a second argument of getJSON function :
self.searchPatients = function () {
$.getJSON("/api/API/GetPatients", { param1: 'anyvalue' }, function (data) {
ko.mapping.fromJS(data, {}, self.patients);
});
};
self.searchPatients();
Assuming the server method looks like as follow :
[HttpGet]
public Object GetPatients(String team)
{
// return the patients
}
You should use this JavaScript :
self.searchPatients = function () {
$.getJSON("/api/API/GetPatients", { team: self.selectedTeam() }, function (data) {
ko.mapping.fromJS(data, {}, self.patients);
});
};
Because self.selectedTeam is an observable you can't send it to the server.What you want to send is its value. That's why you need to 'call' the observable.
self.selectedTeam() // returns the value of the observable.
I hope it helps.
To pass data to controller you can use jquery ajax call as follows,
$.ajax({
type: "POST",
url: "api/API/GetPatients",
data: JSON.stringify(yourObject), // data to be passed to controller
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// your success call
},
error: function () {
alert("Unable to Save.");
}
});