How to call a server-side function from javascript in MVC? - javascript

I am doing amendments in my MVC application in order to disallow users to open more than one tab/ window within a single session.
I am taking reference of this article (click here) in order to do that.
This article is written for asp.net whereas I need to implement this feature for ASP.NET MVC.
I think all this should be possible in MVC, however, I am not sure what should I do to re-write this
if(window.name != "<%=GetWindowName()%>")
GetWindowName() is a function I have created in my Controller, and it returns a value of "WindowName" key from Session object. How can I read its value in above javascript?

You can write a controller method for that:
public ActionResult GetWindowName()
{
Session["WindowName"] =
Guid.NewGuid().ToString().Replace("-", "");
return Json(Session["WindowName"].ToString());
}
Then call it through ajax:
$.get('#Url.Action("GetWindowName")', function(data){
if(window.name != data) {
// do what you need to do here
}
})

You can use ajax for that (jQuery):
$.get('#Url.Action("GetWindowName")', function(result){
if(window.name != result)
//...
});
This is razor syntax...

Related

How to pass the action and controller to the #Url.action call

I would like to pass the action name and controller name to the #Url.action call within a Javascript function as variables. Is there a method to achieve this?
function list_onSelectionChanged(e) {
var strActionName = "Map";
var strControllerName = "PMO";
$("#content").load("#Url.Action(strActionName,strControllerName)");
}
You can't pass them from client-side code in this way because the server-side code has already run at that point. Specify them directly in the server-side operation:
function list_onSelectionChanged(e) {
$("#content").load("#Url.Action("Map", "PMO")");
}
Note that it looks like the syntax will fail because of nested double-quotes. However, keep in mind that the Razor parser identifies the server-side code separately from the client-side code. So this is the entire server-side operation:
Url.Action("Map", "PMO")
And the result of that operation is emitted to the client-side code:
$("#content").load("result_of_server_side_operation");
I was able to modify the script as follows:
function list_onSelectionChanged(e) {
var url = e.addedItems[0].path;
$.get(url, function (data) {
$("#content").html(data);
});
}
Even simpler:
$("#content").load(url);
This allows a variable to be passed for the url.

Unity - communicating with clientside Javascript and ajax. How to pass data back to the webpage from unity?

What I am really asking is this; if there are dependencies which are impossible to compile into the unity build, is there a way of still calling them from within the unity and simply using the scripts loaded into the browser from the website and communicating with them?
Relevant documentation does not address this deeply:
https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
I am creating a website wrapper for a unity application. The buttons for the experience are located within the website, as the buttons affect the rest of the site, not just the unity application.
When certain content is loaded in the unity game play however, the app needs to be able to affect the website. Is there a way to pass the data back to the website in a creative way? Currently, I am including all my javascript code for the website in the unity compile, and it is erroring out on:
gameInstance = UnityLoader.instantiate("gameContainer", "/Build/DomumProto16_Web.json", {
onProgress: UnityProgress
});
Sending data to the gameplay from the website:
gameInstance.SendMessage('Manager','Filter', JSON.stringify(filterActive));
Need to call this function from the unity gameplay. However, ajax.ajax_url is undefined due to it being localized using wp_localize_script() on the backend.
function showStudentWork(studentIndex){
//make sure to remove all the
var x = document.getElementById("studentWork");
var studentID = studentWork[studentIndex];
console.log(studentID);
$.ajax({
url: ajax.ajax_url,
type: "POST",
data: {
action: 'getStudentPost',
currentStudent: studentID
},
success: function (data) {
x.innerHTML = "";
x.innerHTML = data;
x.style.display = "grid";
},
error: function (error) {
console.log(`Error ${error}`);
}
});
return false;
}
What I am really asking is this; if there are dependencies which are impossible to compile into the unity build, is there a way of still calling them from within the unity and simply using the scripts loaded into the browser from the website and communicating with them?
Here are two methods. One is, in my opinion, easier, but it is deprecated and you should ~not~ use it. Options two is the 'corrrect' way, but it is kinda ugly imo.
Option 1: Application.ExternalCall
Documentation
This option allows you to call browser javascript directly, but Unity has deprecated support for it and is probably a bad idea for anything long term.
In a given browser with a Unity web player working, consider the following:
In browser source, define a javascript function
<other html>
<script>
function foo(msg) {
alert(msg);
}
</script>
In Unity, whenever it is nessecary:
Application.ExternalCall( "foo", "The game says hello!" );
This allows Javascript to be called from Unity.
There is similar functionality for communication in the opposite direction.
Option 2: jslibs
Documentation
This is the unity-endorsed way of doing things. It involved packaging javascript libraries into your games.
First, create a javascript file that will be packaged with your game. Here is an example file:
// Unity syntactic sugar
mergeInto(LibraryManager.library, {
// Declare all your functions that can be called from c# here
alert_user: function (msg) {
window.alert(msg);
},
other_func: function () {
// does something else
// etc.
// put as many functions as you'd like in here
}
}
Place that file, with extension .jslib in your Plugins folder on your project.
Then, in your c# files, you need to:
// Declare a monobehavior, whatever
using UnityEngine;
using System.Runtime.InteropServices;
public class NewBehaviourScript : MonoBehaviour {
// IMPORTANT
// You have to declare the javascript functions you'll be calling
// as private external function in your c# file. Additionally,
// They need a special function decorator [DllImport("__Internal")]
// Example:
[DllImport("__Internal")]
private static extern void alert_user(string msg);
// With that unpleasantness over with, you can now call the function
void Start() {
alert_user("Hello, I am a bad person and I deserve to write c#");
}
}
Et viola. You can call other javascript from your c# javascript, and interact with the dom, but I will leave all those decisions up to you.
The other direction
In both cases, communication in the opposite direction (browser saying something to Unity) is the same format.
In javascript, create a UnityInstance (the way of this is a little two long-winded to put into this answer, check either docs). Then, just .sendMessage.
e.g.:
c#
...
void DoSomething (string msg) {
// this is a c# function that does something in the game
// use your imagination
}
...
javascript:
let game = UnityLoader // Actually load the game here
game.SendMessage('TheNameOfMyGameObject', 'DoSomething', 'This is my message');
If I understand it can be done using WWW call function
This is not a proper code okay . This will be just an idea for you.
Send a variable to the PHP function like this
string url = "" // add your URL here;
WWWForm form = new WWWForm ();
form.AddField("YourFunctionName", "SampleFunction");
WWW www = new WWW(url, form);
yield return www;
Now in your PHP do it something like this
function YourFunctionName()
{
// your function code here
}
and now on
$YourFunctionName = $_POST["functionName"];
switch ($functionName){
case "SampleFunction":
SampleFunction();
break;
}
So the idea here is still you will need a PHP and from that PHP call your ajax :)

Insert Javascript variable into Html.Partial ViewDataDictionary ASP.NET MVC

I have a javascript function and when it is called I want to insert a partial into a div. All is working fine, but, when I want to pass some javascript into Html.Partial ViewDataDictionary, it isn't passing the rendered javascript.
<script>
function addExperience() {
#{var uid = #MvcHtmlString.Create("new Date().getTime()");}
console.info(#uid); //output ok !
var partialView = #(Html.Raw(JsonConvert.SerializeObject(Html.Partial("~/Views/Dashboard/_editUserExperience.cshtml", Model, new ViewDataDictionary { { "id", uid } }).ToString().Trim('"'))))
$("#newExperienceSection").append(partialView); //it renders "new Date().getTime(), not the number
}
</script>
Thank you !
If you call Jsonconvert.SerializeObject with a string (Html.Partial returns a string), it returns a string.
So you statement
var partialView = ... will be rendered as
var partialView = "the contents of the partial view";
That's why, when you do this:
$("#newExperienceSection").append(partialView);
it actually displays the javascript as text.
If you want to get a partial view to execute javascript, you can return javascript inside script tags, and as soon as you add that to the DOM it gets executed, for example if you set your _editUserExperience.cshtml as this:
<script>
alert('this gets executed as soon as you do add this to the DOM with the jQuery append command');
</script>
When you execute $("#newExperienceSection").append(partialView); you'll see the alert.
An easier way to insert a partial view is to take advantage of $.ajax, for example, in addExperience:
$.get('#Url.Action("ActionMethodThatReturnsPartial", "YourController")').done(function(theHtmlReturned) {
$("#newExperienceSection").html(theHtmlReturned);
});
($.get is just shorthand for $.ajax using a get request)
Source: http://api.jquery.com/jquery.ajax/
http://api.jquery.com/jquery.get/
http://api.jquery.com/category/deferred-object/

ASP.net javascript call code behing method

I am creating a asp.net web application and I want to know how to call, code behind method in javascript. Following Java script shows that getting the values of multiple textboxes with same name in to array.
using code behind method, I try to pass the values of an array ,but it didn't works. when I am using alert box, it display the textbox values .
function JavaScriptFunction() {
var arr = $("input[name='multiple[]']");
$.each(arr, function (i, item) {
alert($(item).val());
});
}
When I am call code behind method before alert box method, then it won't display any message box. (Testing code behind method)
function JavaScriptFunction() {
var arr = $("input[name='multiple[]']");
$.each(arr, function (i, item) {
PageMethods.setemail("Paul Hayman");
alert($(item).val());
});
}
This is my testing code behind method. TextBox1 I used just for testing.
[WebMethod]
public void setemail(string p)
{
TextBox1.Text = p;
}
Then finally I import webService reference.
using System.Web.Services;
This is I used webforms for button
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="JavaScriptFunction()" OnClick="Button1_Click" />
WebMethod can't interact directly with the DOM. WebMethods are outside the scope of the normal page model.
In fact, WebMethod is no longer supported by MS and you shouldn't use it. Instead, if you're on .NET 4.5 you can create a Web API and call into it with AJAX (jQuery has great helper functions for this, I see you tagged it). The Web API will return the string, and then you can use JavaScript to set the text of the textbox.
Web API
public class TestController : ApiController
{
public string GetHello(string name)
{
return String.Format("Hello, {0}!", name);
}
}
Then the jQuery AJAX code:
$.ajax({
url: '/api/test/GetHello?name=Nade',
type: 'GET'
})
.success(function(output){
$('#TextBox1').val(output);
});
If you're not on .NET 4.5, upgrade! If upgrading isn't possible, then you could just set up a generic handler (.ashx) and write to the response.

Overriding Backbone's URL function to Fetch Data From Local Store

I am writing a caching system which works with backbone (which I am still new to).
The system is as follows:
First try to get the data from local storage and upon failing to do so then make the call to the server.
Can I overwrite the url() function to first check local storage and then make the call or should this mechanism be outside url() and backbone ? i.e. Maybe this is using backbone incorrectly ?
Thanks !
Edit:
As requested I am adding more details.
I am using backbone.js the specific library I am using via require.js is backbone_amd-min.
Code sample:
Model:
define([ 'jquery', 'underscore', 'backbone', 'cacher' ], function($, _, Backbone, cacher) {
var article = Backbone.Model.extend({
defaults : {
title : '',
content : '',
},
parse : function(response, xhr) {
return response;
},
url : function() {
//What I want to do is (specify where to retrieve the article):
var articleInCache = cacher.inCache(this.flag);
if(articleInCache)
return localStorage
else
return remoteUrl;
},
flag : '2'
});
return article;
});
Can I modify url() or should I be modifying fetch()
To answer this question you first need a quick primer on fetch. When you do:
someModel.fetch();
What happens behind the scenes is:
fetch uses the url (or urlRoot) method/property to figure out where to make the AJAX call
fetch uses the sync method to actually make the AJAX call.
After the AJAX call returns, fetch passes what it gets back through parse, then passes that to set.
Given that, you clearly don't want to override url, as it has nothing to do with the actual AJAX part that you want to replace. You could override fetch, and that would work:
fetch: function() {
var fetched = this.getLocalVersion();
if (fetched) {
return new $.Deferred().resolve();
} else {
return this.prototype.fetch.apply(this, arguments);
}
}
However, that won't help you when you want to save or delete your Model, so really sync (which covers all AJAX operations) is probably the ideal method to override.
... of course, there's no point in re-inventing the wheel, so rather than override anything your best bet is probably to use one of the existing Backbone LocalStorage libraries.

Categories