C# property value doesn't get modified within Javascript/ jquery - javascript

I initialize a property within the Controller's Constructor.
public BookController()
{
SessionProvider.SessionLoadSceanrio = false;
}
I have an Action Method which reset the property again on a button click event.
public ActionResult LoadScenario(int bookId)
{
SessionProvider.SessionLoadSceanrio = true;
// remaining code
return Json(ScenarioId, JsonRequestBehavior.AllowGet);
}
Following javascript code is in my view which is called when the button is clicked.
var BookHandler = {
$("#btnLoadScen").click(function (e) {
$.ajax({
url: "#Url.Action("LoadScenario", "Book")",
dataType: 'json',
type: 'POST',
data: {
'bookId': BookHandler.getBookId()
},
success: function (response) {
var scenarioId = response;
var isLoadScenario = "#Portal.Presentation.Web.Planning.MVC.App_Start.SessionProvider.SessionLoadSceanrio";
//otherproperties
window.open("#Url.Action("Index", "BookScenario", new {loadScenario = "_loadScenario"}).replace('_loadScenario', isLoadScenario), tabId);
},
error: function () {
}
});
});
}
My problem is when I click the button, value of property changes in the Controller. But it doesn't change in my javascript code.Please see the screen capture of the developer tool.
does Anyone has a clue on this?

You are using the razor syntax. then initially page loaded , values are set, and these values are string , not a variable anymore. then you can't get session value updated again.
please get session value from an AJAX call and set to your variable.

The code below will only be evaluated once you get the view from server and will not be re-evaluated after your ajax call.
var isLoadScenario = "#Portal.Presentation.Web.Planning.MVC.App_Start.SessionProvider.SessionLoadSceanrio";
In order to do what you intended, you will need to return SessionLoadSceanrio in your response.
You can do it like:
public ActionResult LoadScenario(int bookId)
{
SessionProvider.SessionLoadSceanrio = true;
// remaining code
return Json(new {ScenarioId, SessionLoadSceanrio = SessionProvider.SessionLoadSceanrio}, JsonRequestBehavior.AllowGet);
}

Related

How to execute a controller method call in Javascript

Good afternoon!
I have the following controller action:
[HttpPost]
public ActionResult ShowComparisonResultSimpleViewFromJs(List<GetDocumentList_Result> documents,
GetAgreementNumberKktShiftInfo_Result infoResult)
{
ViewBag.DisplayName = CurrentUser?.DisplayName;
ViewBag.Documents = documents;
ViewBag.DocumentCount = Convert.ToString(documents.Count());
return View("ComparisonResultSimpleView", infoResult);
}
I also have an InputKktShiftView view that has a button click handler. In it I need to call the controller method specified above, as a result, the ComparisonResultSimpleView page is loaded.
Here is an example of a button click handler:
<script>
function OnClick(s, e) {
//Data for example:
var parameterModel = {
FnFactoryNumber: '1',//'9280440300664345',
ShiftNumber: 38
};
$.ajax({
type: 'POST',
url: '/TaxcomProblems/GetInputKktShiftJsonResult',
data: parameterModel
}).success(function(data) {
if (data.IsValid) {
if (data.InfoResult != null) {
var jsData = {
documents: data.Documents,
infoResult: data.InfoResult
};
//Here you need to call the /TaxcomProblems/ShowComparisonResultSimpleViewFromJs method
//$.ajax({
// type: 'POST',
// url: '/TaxcomProblems/ShowComparisonResultSimpleViewFromJs',
// data: jsData,
// dataType:'html',
// success: function(result) {
// var view = $("ComparisonResultSimpleView");
// view.html(result);
// }
//});
} else {
dxConfirm("Перейти на страницу выбора ККТ?")
.success(function() {
window.location.href = "/TaxcomProblems/ShowChoiceKktView";
});
}
}
});
}
Here is the code for my ComparisonResultSimpleView page:
#using System.Web.UI.WebControls
#using BonusProgramAPI.Tools
#model BonusProgramAPI.EF.GetAgreementNumberKktShiftInfo_Result
#{
ViewBag.Title = "Результаты для ККТ и смены";
ViewBag.agreementNumber = Model?.agreementNumber;
ViewBag.outletId = Model?.outletId;
ViewBag.fnFactoryNumber = Model?.fnFactoryNumber;
ViewBag.openDateTime = Model?.openDateTime.ToString("dd-MM-yyyy hh:mm:ss");
ViewBag.shiftNumber = Model?.shiftNumber;
}
<script>
function OnBtnGetKktInfoClick(s, e) {
pcKktInfo.Show();
}
</script>
#Html.DevExpress().FormLayout(settings =>
{
settings.Name = "rootLayout";
settings.Items.AddGroupItem(group =>
{
#* some code *#
}
}).GetHtml()
#* PopupControls: *#
#{
Html.RenderPartial("PopupControlKktInfoPartialView");
Html.RenderPartial("PopupControlShiftInfoPartialView");
}
Question: How do I call the ShowComparisonResultSimpleViewFromJs method of the TaxcomProblems controller so that the ComparisonResultSimpleView page displays?
P.S.: If I use ajax, then I call the specified method correctly (all data is transferred to it correctly), but the specified page is not displayed, and the current page remains.
Ajax post will not refresh the page. You have to do it by yourself. Also you are sending the full page from the ShowComparisonResultSimpleViewFromJs action with the following code:
return View("ComparisonResultSimpleView", infoResult);
What you can do is make the ShowComparisonResultSimpleViewFromJs action return partial content (html) instead of full page content. And then add the returned data in a div on the success method of the ajax call.
To return partial view write:
return PartialView("~/views/ComparisonResultSimpleView.cshtml", infoResult);
Also in the javascript codes note that the element selector is missing a class or Id notation. You can simply write:
$("#ComparisonResultSimpleView").html(result);
Your jquery selector is attempting to get the element
<ComparisonResultSimpleView></ComparisonResultSimpleView>
from here
success: function(result) {
var view = $("ComparisonResultSimpleView");
view.html(result);
}
Do you mean to select the element with id = ComparisonResultSimpleView ?
<div id="ComparisonResultSimpleView"></div>
You will need to add "#" to your selector like so:
success: function(result) {
var view = $("#ComparisonResultSimpleView");
view.html(result);
}
Want to know if the selector is correct?
Run the following line in your page's browser console
$("#ComparisonResultSimpleView").length; // greater than zero means the number of elements matching selector. Zero means no match.

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

Calling a HTTP POST method in a MVC Controller from the View's Javascript & Database saving

I am trying to update a value in my database. When the user presses the update button this script is called.
View Code:
<script>
function scr_UpdateQuote(field) {
var r = confirm("Are you sure you want to update your quote?");
if (r == true) {
var textBox_UserTitle = document.getElementById(field);
*CODE TO POST METHOD HERE*
}
}
</script>
In the controller, the value is then revived and saved into the database. A message is sent back to let the user know their quote was updated.
Controller Code:
[HttpGet]
public ActionResult UpdateQuote(string newQuote)
{
*REPLACE QUOTE IN DATABASE*
ViewBag.QuoteUpdated = "Your Quote has been updated.";
return View();
}
I am having difficulty finding out how to write the code described between the **'s
(For the database part I have a user-id that can be used to identify the row)
You can use form posting like this:
$("#YourForm").submit(function() {
$.post("/YourController/UpdateQuote", $("#YourForm").serialize())
//this will serialize your form into:
// newQuote=someValue&&someOtherVariable=someOtherValue etc.
.done(function(data) {
// do what ever you want with the server response
});
})
or you can use an ajax post:
$.ajax({
type: "POST",
url: "/YourController/UpdateQuote",
data: {newQuote: document.getElementById(field)},
dataType: "json",
success: function(data) {
// do what ever you want with the server response
},
error: function(){
// error handling
}
});
For using the data, assuming you have an DbContext called MyDbContext:
[HttpGet]
public ActionResult UpdateQuote(string newQuote)
{
// get userID somehow, either from session, or pass as another parameter here
using (var dc = new MyDbContext)
{
var quoteToUpdate = dc.QuotesTable.FirstOrDefault(q => q.UserID == userID)
quoteToUpdate.quoteColumn = newQuote;
dc.SaveChanges();
}
ViewBag.QuoteUpdated = "Your Quote has been updated.";
return View();
}

using ViewBag - asp.net mvc

In a asp.net mvc project i have this on top of my index.cshtml file
$.ajax({
url: '#Url.Action("getLoggedUser", "Home")',
dataType: "html",
"async": true,
type: "GET",
success: function (data) {
},
});
And the method it uses is this one, that is on HomeController
public async Task getLoggedUser()
{
try
{
BenchesService benchService = new BenchesService();
UserTest LoggedUser = new UserTest();
string name = Request.RequestContext.HttpContext.User.Identity.Name;
name = name.Substring(name.LastIndexOf('\\') + 1);
LoggedUser = await benchService.getCurrentUser(name);
role = LoggedUser.role;
ViewBag.LoggedUser = LoggedUser.role;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
This does a GET to the server with getCurrentUser(name); and that returns a json with user info, that i use to fill a UserTest object (i checked with break and the LoggedUser is filled correctly).
I want to save the user Role, to use in the html / javascript part
Then again on my index.cshtml i have this other script
$(document).ready(function () {
setTimeout(function () {
console.log("TIMER!");
userRole = '#ViewBag.LoggedUser';
alert(userRole);
}, 5000);
My problem is that the alert shows a empty message, like the ViewBag.LoggedUser has nothing. am i using ViewBag wrong?
Are you reloading your page? If not, your ViewBag has the same content like in the moment when page was rendering. Razor render text from ViewBag only on creation of html page, and if you are not reloading page, it will be always empty. You have to return your data in some object (ex. json) to ajax request and then you can use it.

Categories

Resources