Asp.net MVC-5 working with bootstrap toggle switch - javascript

I am working on asp.net MVC 5, referring to my question i have added a bootstrap toggle switch in my page, the razor syntax is bellow
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset style="height:60px">
<legend style="text-align:center; font-size:large; font-family:'Times New Roman'; background-color:#C8E6C9; color:red">Remote On/Off</legend>
<input id="test_id" name="cmdName" type="checkbox" checked data-toggle="toggle">
</fieldset>
}
This razor syntax is placed in a partial view and is called in a layout
The generated Switch button is as follows
Now, i want to pass this On or Off value(string) to my action method.
For start i have placed a javascript event function and which simply shows me the alert box displaying On or Off with respective switch condition
My script is as follows
<script>
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
alert("ON");
} else {
alert("Off");
}
}); </script>
For passing this On or Off i have searched many articles and found that ajax call is used for this purpose so i placed a ajax call in my if and else condition
if ($(this).is(":checked")) {
$.ajax({
url: '#Url.Action("MultiGraph")',
data: '{"cmdName": "On"}',
success: function (data) {
alert(data);
}
});
} else {
$.ajax({
url: '#Url.Action("MultiGraph")',
data: '{"cmdName": "Off"}',
success: function (data) {
alert(data);
}
});
}
Bellow is my action method
public ActionResult MultiGraph(string search, string start_date, string cmdName , string End_date,int? page)
{
// i want to pass On or Off values based on switching in my string cmdName
}
Is there any other way rather than ajax call to do it? Or what should i do in my ajax call ?
Updated Code
In my script i have done the following
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
//alert("ON");
var data = { cmdName: "On" }
} else {
//alert("Off");
$.ajax({
url: '#Url.Action("MultiGraph")',
data: data,
});
}
});
See the bellow images
Getting null in cmdName
I am unable to pass them, i must be missing some thing which i don't know
Any help would be appreciated

Related

How do I insert a PartialView into a normal View using an Ajax-Function in ASP.NET Core 3?

This is the site.js code I am using to insert the PartialView into the main View.
$("#btn2").click(function () {
$.ajax({
url: "/Home/RefreshDoors",
datatype: "text",
type: "POST",
success: function (data) {
$('#DoorBox').html(data);
},
error: function () {
$("#DoorBox").html("ERROR");
}
});
});
I want to place the resulting table inside a box (div with the id="DoorBox") however as a result I get a raw view of the returned Door-Json-Objects:
(imgur-link to screenshot)
This is the div-code inside the view:
<div id="DoorBox">
</div>
This is the code from the HomeController I use to render the PartialView:
[HttpPost]
public PartialViewResult RefreshDoors()
{
return PartialView("_Doors", RefreshDoorsFunction().Result);
}
How do I get the code to insert the PartialView (just a table with the properties of the door-model displaying the doors)) to render within the div-box (without refreshing the page)?
Edit: Here is the code from the RefreshDoorsFunction():
public async Task<List<NewDoor>> RefreshDoorsFunction()
{
string token = await _auth.GetTokenAsync();
_doorList = SecureRestCall.GetDoorListAsync("https://exampleapi.azurewebsites.net", token);
return _doorList.Result;
}
I got the answer. Turns out I'm just stupid: I used the wrong button to test the ajax function (wrong id assigned to the button). It works now. Sorry for wasting some people's time.

ASP.net: AJAX Result Not Kicking Off

I think this will be a weird one for you as I am at my wits end with this. On a screen I have in a table, I have a link being clicked that is setting off a javascript/ajax request. I have similar code in another screen that works perfectly as it heads down into the success part of the ajax call and runs code in the success portion of the call. For some reason though I can't seem to get this to work and when I debug it in chrome, I lose my breakpoints and it never seems to get into the success portion of the Ajax call.
#section scripts{
<script>
// Get the bond ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.updatelink').click(function () {
var bondid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Maintenance/Bond_Maint?handler=UpdateandReloadData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { bondid: bondid },
success: function (result) {
if (result.pass != undefined) {
document.forms[0].submit();
}
},
});
});
</script>
}
The ASP.net code behind that is calling does an update to the database and then passes back a variable containing Success as its message.
//-------------------------------------------------------------------------------
// Try to get and insert the data from a selected row and copy it
//-------------------------------------------------------------------------------
public ActionResult OnPostUpdateandReloadData(string bondid)
{
return new JsonResult(new { pass = "Success" });
}
I'm not sure how else to describe my issue other than when I debug my other code via the browser, it appears to take a different path than this code does and I cannot fathom why. For reference my other code looks like this:
#section scripts{
<script>
// Get the offender ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var offenderid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.path != undefined) {
window.location.replace(result.path);
}
},
});
});
</script>
}
Any help would be appreciated.
Okay guys so first off, thank you everyone for responding to my question. Frank Writte and Alfred pointed me into the right direction by looking for the status in the network tab for my calls. I found out that I was getting cancellations for my requests. After looking into that I found this article What does status=canceled for a resource mean in Chrome Developer Tools? that has an answer from FUCO that gave me what I needed to do. Apparently I needed to add event.preventDefault(); in front of my ajax call and all of a sudden my code worked. I'm not sure I completely understand why this works but I can't complain about the results. Again thank you everyone for trying to help. This one has been boggling my mind all morning.

Redirect to another page after Ajax call?

so this is a hard one for me to try and explain. I have a razor page that when a button is clicked it calls a javascript function which makes an ajax call to a handler in the back end. The handler does some stuff and gets a id that I want to pass to another page. I am trying to use the RedirectToPage function in the back end but the screen never opens. It successfully calls the handler but when the handler does its return, nothing happens. Is there a way to do this?
Here is the javascript/ajax code that gets called from a button being clicked.
#section scripts{
<script>
// Get the account ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var accountid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
},
});
});
</script>
}
For my code behind code that I am calling from the ajax call, that's below here:
public ActionResult OnPostCopyData (string accountid)
{
// Do my other stuff here
return RedirectToPage("Account_Information", new { id = account.Account_ID });
}
Any help would be appreciated and if doesn't make sense, I can try and clear up any questions.
I think this is what you want, I did something similar in an MVC 5 project and I haven't tested it in Razor Pages yet:
This would be your method, note that you should add your Controller to the Url.Action, and I personally haven't tried passing a parameter along with the url but I image it'll work just fine
[HttpPost]
public ActionResult SubmitSomething()
{
return Json(new { redirectUrl = Url.Action("Account_Information", "YOUR_CONTROLLER_NAME", new { id = account.Account_ID }) });
}
And then this would be your Ajax request, I updated the success portion
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var accountid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.redirectUrl !== undefined) {
window.location.replace(result.redirectUrl);
} else {
// No redirect found, do something else
}
},
});
});
This isn't tested, so I can only hope that it works for you right now
Edit: Updated the Url.Action to use OP's view names and parameters
Redirect to page returns a 301 response, which will be in the format:
HTTP/1.1 301 Moved Permanently
Location: http://www.example.org/index.asp
To redirect after the ajax call you can redirect to the requested url by:
success: function (result) {
window.location = result.getResponseHeader('Location');
}

ASP MVC Refresh partial view grid

I am trying to refresh a partial view grid after changing a record.
I have a button where the user can click on, than it will change a row in the grid. This works OK, however. I have to manually refresh the page to see the modification. Now I thought I could make a new JavaScript Ajax function to do this. So after the user push the button it will load the function RefreshGrid
JavaScript Function:
function RefreshGrid() {
var numberPlate = $("#NumberPlate").val();
if (numberPlate) {
$.ajax({
type: 'get',
url: appPath + '/Service/Grid',
data: { numberPlate: numberPlate },
success: function (response) {
$("#Grid").html(response);
},
error: function (response) {
$("#dialog .modal-body").html(msgErrorDuringRequest);
$("#dialog #dialog-title").html(errorTitle);
$("#dialog").modal("show");
}
});
}
}
Now the controller
public ActionResult Grid(string numberPlate)
{
IList<ServiceOrder> services = ServiceRepository.Services(numberPlate);
return PartialView("_Grid", services);
}
For some reason it is returning me the error function
error: function (response) {
$("#dialog .modal-body").html(msgErrorDuringRequest);
$("#dialog #dialog-title").html(errorTitle);
$("#dialog").modal("show");
}
But I have no idea where it goes wrong. Cant really imagine it is in the controller as I have a familiar function elsewhere which works flawless but perhaps I am missing something.
try code:
Remove The All your jquery code ,just used below the code your RefreshGrid Function
var numberPlate = $("#NumberPlate").val();
var url= '/Service/Grid?numberPlate='numberPlate;
$("#Grid").load(url);

After show Modal Window jQuery validation plugin doesn't work

I have a problem with jQuery Validation Plugin.
I used ASP.NET MVC with Entity Framework. The project has a lot of libraries and it's hard to understand the problem and find answer.
I have a form on which the section with fields. I used validation plugin for validate client-side fields.
The section is collapsible and can to be open and closed. Inside section I have button for open modal window. Inside window I can to search data used Ajax. User can to add information manually, can add information used Ajax and fields can be empty.
The first task is to add validation for hidden fields.
I added setDefault for validator inside $(document).ready:
jQuery.validator.defaults.ignore = "";
When I added setting ignore for validator, everything work fine with hidden fields and open fields but after showing modal window validator plugin doesn't work. In FireBug I take error: TypeError: validator is undefined (twice).
I open and close the modal window (without Ajax search) and I take this error and validator doesn't work.
This is modal window code:
#using (modal.BeginBody()){
<div class="row">
<div class="col-lg-offset-3 col-lg-6" id="search-entry-form">
#using (var form = Html.Bootstrap().Begin(new Form().HtmlAttributes(new { onsubmit = "return false" })))
{
#form.FormGroup().TextBoxFor(model => model.EANCode).Label();
#form.FormGroup().TextBoxFor(model => model.Name).Label();
#form.FormGroup().TextBoxFor(model => model.InternationalName).Label();
#Html.Bootstrap().Div(Html.Bootstrap().SubmitButton().Text("Wyszukaj").Id("search-specific").Style(ButtonStyle.Success).
ButtonBlock().PrependIcon("glyphicon glyphicon-search")).Class("col-lg-5 col-lg-offset-7");
}
</div>
</div>
<div class="col-lg-12 top30" id="result-table"></div>}#using (modal.BeginFooter()){#Html.Bootstrap().Button().Text("Zamknij").Data(new { dismiss = "modal" }).Style(ButtonStyle.Primary)}
I this file I added Bundels with Ajax code:
#Scripts.Render("~/bundles/specificNutSearch")
This is Ajax code:
$(document).ready(function () {
function pagination() {
$('#result-table').each(Utils.Pagination);
}
function getData(id) {
$.ajax({
url: "GetSpecific",
dataType: "json",
method: "POST",
cache: false,
data: {
id: id
},
}).success(function (result) {
if (result === null) return;
for (var propName in result) {
$(".panel [Name$='." + propName + "']").val(result[propName]);
}
clear();
});
}
function clear() {
$("#result-table").html("");
$(".modal input").val("");
$(".pager").remove();
}
function search() {
var form = $("#search-entry-form :input").serialize();
$.ajax({
url: $('#search-entry-form form').attr('action'),
dataType: "html",
method: "POST",
cache: false,
data: form
}).success(function (result) {
$("#result-table").html(result);
$(".select-specific").on("click", function () { getData($(this).data("specific")) });
pagination();
});
}
$("#search-specific").on("click", search);});
This is the field code which need validate:
Html.Bootstrap().Div(
Html.Bootstrap().Label("").LabelText("4.").Class("pull-left"),
Html.Bootstrap().FormGroup().TextBoxFor(model => model.EAN).Label()).Class("col-lg-6")
In the chhtml view I added modal window on the bottom file:
<div class="modal fade" id="specificNutritionalPurposeSearch" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
It is ViewModel field:
[Display(Name = "Kod EAN")]
[RegularExpression("[0-9]{13}",ErrorMessage = "Kod EAN powinien zawierać 13 znaków")]
public string EAN { get; set; }
Also found a very strange thing:
When I Comment out the all specificNutSearch (#Scripts.Render("~/bundles/specificNutSearch")) code, the plugin does not work.But when I comment out #Scripts.Render("~/bundles/specificNutSearch" line, plugin works.
What could be the problem? Maybe that's a problem of incompatibility of versions jQuery and Validator Plugin?
EDIT:
This is button code for open model window:
#Html.Bootstrap().Button().Text("Wyszukaj środek spożywczy").TriggerModal("specificNutritionalPurposeSearch").HtmlAttributes(new { href = Url.Action("SearchSpecificNutritionalPurpose") }).Style(ButtonStyle.Success).ButtonBlock().PrependIcon("glyphicon glyphicon-search")
This is ActionResult in Controller:
[HttpGet]
public ActionResult SearchSpecificNutritionalPurpose()
{
var model = new SpecificNutritionalPurposeSearchViewModel();
return PartialView("Modals/_SpecificNutritionalPurposeDictionarySearch", model);
}
In action model empty because modal window has button for searching data.
This is ActionResult for search button in modal window for searching data:
[HttpPost]
public virtual ActionResult SearchSpecificNutritionalPurpose(SpecificNutritionalPurposeSearchViewModel searchParameters)
{
var searchResult = _dictionaryRepository.FindSpecificNutritionalPurpose(searchParameters.EANCode, searchParameters.Name, searchParameters.InternationalName).Take(100).ToList();
return PartialView("Modals/_SpecificNutritionalPurposeSearchResult", searchResult);
}
Method FindSpecificNutritionalPurpose take data from dataBase (EF)
I think that when the specyficNutSearch script alters the DOM the validation handlers are getting removed.
My solution is to change clear method so it will refresh validation handlers:
function clear() {
$("#result-table").html("");
$(".modal input").val("");
$(".pager").remove();
//add this
var $form = $("#search-entry-form form");
$form.removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($form);
}

Categories

Resources