DotNet Core calling method via onscreen button - javascript

In my DotNet Core application, I have a button set up with the some javascript placed in for my OnClick event. It looks like this:
<div>
#(Html.DevExtreme().Button()
.Text("Press me")
.Type(ButtonType.Normal)
.Width(90)
.OnClick("notify")
)
</div>
<script>
function notify() {
console.log("pressed");
// ModifiedDuration.AdjustmentScreen_Netting.Csharp.RunBatch();
// var a = '<%=RunBatch()%>';
}
</script>
The commented out lines are what I've tried to call my target method but neither have worked. The underlying method I want to call is this:
public void RunBatch()
{
Console.WriteLine("Re-running batch");
TestOutput print= new TestOutput ();
print.TestMethod();
}
Then, what TestMethod does:
public void ProcessAdjustedBatch()
{
Console.WriteLine("I have been called from the datagrid!!!!");
}
So after I press the button, I would expect to see the following log messages:
Pressed
re-running batch
I have been called from the datagrid!!!!
But all that I see is Pressed in my dev log. How can I achieve my intended output?

Console.WriteLine() will never shown in client's browser because it runs server-side and opened in server's console window. It is necessary to use Debug.WriteLine() if you want to see debug messages in immediate output window.
Also note that var a = '<%=RunBatch()%>' only executes inside ASPX pages, it cannot be executed in Razor which uses #{ ... } for code segment, and both debug methods are server-side methods.
If you want to show server-side debug message in browser's console with console.log(), you need to create a controller action that executes both methods which have string return type and then use AJAX inside notify() function which outputs the result in success part.
Here is a simple example:
Controller Action
public IActionResult GetMessages()
{
var messages = new StringBuilder();
messages.Append(RunBatch());
messages.Append("\n"); // use newline to separate messages from different methods
messages.Append(ProcessAdjustedBatch());
return Json(messages.ToString(), JsonRequestBehavior.AllowGet);
}
Debug Methods
public static string RunBatch()
{
string batch = "Re-running batch";
Debug.WriteLine(batch);
TestOutput print = new TestOutput();
print.TestMethod();
return batch;
}
public static string ProcessAdjustedBatch()
{
return "I have been called from the datagrid!!!!";
}
View (script tag)
<script>
function notify() {
console.log("pressed");
$.ajax({
type: 'GET',
url: '#Url.Action("GetMessages", "ControllerName")',
dataType: 'json',
success: function (result) {
console.log(result);
}
});
}
</script>
Now the console output should be like this:
pressed
Re-running batch
I have been called from the datagrid!!!!
Live example: .NET Fiddle
Related issues:
Where does Console.WriteLine go in ASP.NET?
Asp.net mvc Console.WriteLine to browser
How to use Console.WriteLine in ASP.Net MVC 3

Related

How to use value from Jquery to Html helper razor

in JavaScript
<script>
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", '#Url.Action("****", "****")',true);
xmlHttpRequest.onloadend = function() {
#{
var res = (UserResponseMvc) TempData["UserResponse"];
}
#Html.ShowAlert(res?.Message)
}
xmlHttpRequest.send();
</script>
in Controller
public ActionResult Upload() {
//code
TempData["UserResponse"] = new UserResponseMvc
{
Success = true,
Message = "Upload Success"
};
return View();
}
In this piece, the code does not know the res variable.
How can I use the res variable here?
I write in Asp.net Mvc code.
Pls help me.
You can like this:
View
<input type="button" value="ClickToSend" onclick="sendToAction()" />
<script>
function sendToAction() {
var res = ["Upload1", "Upload2", "Upload3"]; // Sample
jQuery.ajax({
type: "POST",
url: "#Url.Action("Upload")", // Upload is your action in controller
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(res),
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
Action
[HttpPost]
public ActionResult Upload(List<String> res)
{
return View();
}
I think that can not happen
ShowAlert if only the function displays the message, then it should be a function of javascript.
You can't. and the reason is that they do not "live" in the same time.
The Razor variables are "Server side variables" and they don't exist
anymore after the page was sent to the "Client side".
When the server get a request for a view, it creates the view with
only HTML, CSS and Javascript code. No C# code is left, it's all get
"translated" to the client side languages.
The Javascript code DO exist when the view is still on the server, but
it's meaningless and will be executed by the browser only (Client side
again).
This is why you can use Razor variables to change the HTML and
Javascript but not vice versa. Try to look at your page source code
(CTRL+U in most browsers), there will be no sign of C# code there.
In short:
The server get a request.
The server creates "takes" the view, compute and translate all the C# code that was embedded in the view, to CSS,Javascript, and HTML.
The server returns the client side version of the view to the browser as a response to the request.
the browser renders the page and executes all the Javascripts
Refer to How to pass a value to razor variable from javascript variable?
In your case, I have a some documents for you refer.
jQuery Ajax File Upload
File upload using MVC 4 with Ajax

Call WebMethod in C# codebehind without using a server form in ASPX page

Due to issues with styling, and needing multiple forms on one single web page, I currently have a form that is outside of the normal form with runat=server.
Is it possible for me to still call a WebMethod in the C# codebehind of this web page using ajax? I want to submit the information from this form to the same connection string that I am using earlier in the page, in a different form.
Here is my current code:
$().ready(function () {
$("input[type=submit]").click(function () {
handleClick();
createJob();
});
});
function createJob() {
var txtTestValue = document.getElementById('jobTitle').value;
$.ajax({
// POST signals a data request
type: "POST",
// This directs which function in the c# code behind to use
url: "Account/help.aspx/CreateJob",
// The paramater pageIndex, page number we need to load, to pass to GetCustomers(int pageIndex)
data: txtTestValue,
// Type of data we are sending to the server (i.e. the pageIndex paramater)
contentType: "application/json; charset=utf-8",
// Type of data we expect back from the server (to fill into the html ultimately)
dataType: "text",
// If all goes smoothly to here, run the function that fills our html table
success: OnSuccess,
// On failure, error alert user (aka me so that I know something isn't working)
failure: function (response) {
alert("failure");
},
error: function (response) {
alert("error");
}
});
});
And my WebMethod in the codebehind:
[WebMethod]
public string CreateJob()
{
//rest of my database code here
}
Sorry for the confusion but it's doing everything right up until the ajax code, and then seems to ignore it (and returns that the ajax failed with an error). My code is not reaching the WebMethod and any breakpoints I set in Visual Studio are not triggered in the page header. Thanks in advance for your help!
You need to declare the method as static.
[WebMethod]
public static string CreateJob()
^^^^^
{
//rest of my database code here
}
Another issue is if input[type=submit] is ASP.Net Button control, it will post back to server. You cannot use ASP.Net Server control to make jQuery Ajax call - $.ajax.
// This code won't work if `input[type=submit]` is a server button control
$(function () {
$("input[type=submit]").click(function () {
handleClick();
createJob();
});
});
you need to use regular html input or button control with type=button instead of type=submit.
The webmethod should be static.
[WebMethod]
public static string CreateJob()
{
//rest of my database code here
}

Call razor c# function from javascript function

I have an html link in one file
Home
On click I want a js function(in another file, with extension js) to execute and that is:
function xupdate(string) {
document.title = string;
//Call razor c# function
}
Now I have a c# function(it reads files and displays their information) in a cshtml file:
#helper fileRead(String file) {
var dataFile = Server.MapPath(file);
Array userData = File.ReadAllLines(dataFile);
foreach (string dataLine in userData) {
foreach (string dataItem in dataLine.Split(',')) {
//dataItem <text> </text>
#Html.Raw(dataItem);
}
}
}
I want to call the fileRead function from the js xupdate() function and send the value of string into fileRead as a parameter.Is there a way to do this?
Note: I have already included the html link in the cshtml file and my functions work perfectly. Also I know that I have to include a file extension when calling the c# function.
You can not call C# function from javascript directly, Because javascript execute on client side and C# function execute at server side.
So you must call it other way like AJAX.
Define your function in controller and call it via AJAX call.
Use AJAX:
var ret = null;
$.ajax({
async: false,
url: "YourFunctionName_in_Controller",
dataType: "json",
success: function (data) {ret = data;}
});
return ret;
DotNet.invokeMethodAsync('{ASSEMBLY NAME}', '{.NET METHOD ID}', {ARGUMENTS});
https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-dotnet-from-javascript?view=aspnetcore-6.0

How to use AJAX Post to invoke ASP.NET MVC Controller action and return new View?

I am working a site in ASP.NET MVC where the user is presented with a calendar, and clicking on a particular calendar date invokes the following function:
function selectHandler(event, data) {
var myRequest = new Request.HTML({
url: '/Calendar/EventList',
method: 'post',
data: { datedata: data.toString() },
update: $('postback'),
}).send();
};
I am using the MooTools AJAX classes to invoke my Controller Action /Calendar/EventList, shown below:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EventList(string datedata)
{
CalendarViewData viewData = new CalendarViewData
{ EventList = GetEventsList(datedata) };
return View(viewData);
}
I can set a breakpoint in the EventList action, and see that it is returning the view, but the browser remains on the initial page, and never redirects to the page returned by this EventList action.
I suspect I need to add more to my JavaScript function but am not sure what. Any ideas?
Why would the browser redirect? You are sending an AJAX request to a controller action which returns a view (this probably is wrong, you might need to return a partial view) which is then used to update some element in the DOM. If you want to redirect you could use a simple anchor tag (or a form if you need to POST), no need to use javascript.

Call javascript from MVC controller action

Can I call javascript function from MVC controller action (not from view page) and get return value? How?
I need to make request to server from code (.cs) using javascript like here (but this is aspx page)
function getInitData() {
var code; code = 'return {' ;
code += 'me: API.getProfiles({uids: API.getVariable({key: 1280}), fields: "photo"})[0]';
code += '};'
VK.Api.call('execute', { 'code': code }, onGetInitData);
}
For those that just used a standard form submit (non-AJAX), there's another way to fire some Javascript/JQuery code upon completion of your action.
First, create a string property on your Model.
public class MyModel
{
public string JavascriptToRun { get; set;}
}
Now, bind to your new model property in the Javascript of your view:
<script type="text/javascript">
#Model.JavascriptToRun
</script>
Now, also in your view, create a Javascript function that does whatever you need to do:
<script type="text/javascript">
#Model.JavascriptToRun
function ShowErrorPopup() {
alert('Sorry, we could not process your order.');
}
</script>
Finally, in your controller action, you need to call this new Javascript function:
[HttpPost]
public ActionResult PurchaseCart(MyModel model)
{
// Do something useful
...
if (success == false)
{
model.JavascriptToRun= "ShowErrorPopup()";
return View(model);
}
else
return RedirectToAction("Success");
}
You can call a controller action from a JavaScript function but not vice-versa. How would the server know which client to target? The server simply responds to requests.
An example of calling a controller action from JavaScript (using the jQuery JavaScript library) in the response sent to the client.
$.ajax({
type: "POST",
url: "/Controller/Action", // the URL of the controller action method
data: null, // optional data
success: function(result) {
// do something with result
},
error : function(req, status, error) {
// do something with error
}
});
Yes, it is definitely possible using Javascript Result:
return JavaScript("Callback()");
Javascript should be referenced by your view:
function Callback(){
// do something where you can call an action method in controller to pass some data via AJAX() request
}
It is late answer but can be useful for others.
In view use ViewBag as following:
#Html.Raw("<script>" + ViewBag.DynamicScripts + "</script>")
Then from controller set this ViewBag as follows:
ViewBag.DynamicScripts = "javascriptFun()";
This will execute JavaScript function.
But this function would not execute if it is ajax call.
To call JavaScript function from ajax call back, return two values from controller and write success function in ajax callback as following:
$.ajax({
type: "POST",
url: "/Controller/Action", // the URL of the controller action method
data: null, // optional data
success: function(result) {
// do something with result
},
success: function(result, para) {
if(para == 'something'){
//run JavaScript function
}
},
error : function(req, status, error) {
// do something with error
}
});
from controller you can return two values as following:
return Json(new { json = jr.Data, value2 = "value2" });
There are ways you can mimic this by having your controller return a piece of data, which your view can then translate into a JavaScript call.
We do something like this to allow people to use RESTful URLs to share their jquery-rendered workspace view.
In our case we pass a list of components which need to be rendered and use Razor to translate these back into jquery calls.
If I understand correctly the question, you want to have a JavaScript code in your Controller. (Your question is clear enough, but the voted and accepted answers are throwing some doubt)
So: you can do this by using the .NET's System.Windows.Forms.WebBrowser control to execute javascript code, and everything that a browser can do. It requires reference to System.Windows.Forms though, and the interaction is somewhat "old school". E.g:
void webBrowser1_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
HtmlElement search = webBrowser1.Document.GetElementById("searchInput");
if(search != null)
{
search.SetAttribute("value", "Superman");
foreach(HtmlElement ele in search.Parent.Children)
{
if (ele.TagName.ToLower() == "input" && ele.Name.ToLower() == "go")
{
ele.InvokeMember("click");
break;
}
}
}
}
So probably nowadays, that would not be the easiest solution.
The other option is to use Javascript .NET or jint to run javasctipt, or another solution, based on the specific case.
Some related questions on this topic or possible duplicates:
Embedding JavaScript engine into .NET
Load a DOM and Execute javascript, server side, with .Net
Hope this helps.
The usual/standard way in MVC is that you should put/call your all display, UI, CSS and Javascript in View, however there is no rule to it, you can call it in the Controller as well if you manage to do so (something i don't see the possibility of).
Since your controller actions execute on the server, and JavaScript (usually) executes on the client (browser), this doesn't make sense. If you need some action to happen by default once the page is loaded into the browser, you can use JavaScript's document.OnLoad event handler.
<script>
$(document).ready(function () {
var msg = '#ViewBag.ErrorMessage'
if (msg.length > 0)
OnFailure('Register', msg);
});
function OnSuccess(header,Message) {
$("#Message_Header").text(header);
$("#Message_Text").text(Message);
$('#MessageDialog').modal('show');
}
function OnFailure(header,error)
{
$("#Message_Header").text(header);
$("#Message_Text").text(error);
$('#MessageDialog').modal('show');
}
</script>

Categories

Resources