在JavaScript中访问MVC服务器端变量 [英] Accessing MVC server side variable in Javascript

查看:76
本文介绍了在JavaScript中访问MVC服务器端变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要将一个Web应用程序从Drupal迁移到ASP.net MVC Web应用程序。

I'm moving one of our web applications from Drupal to an ASP.net MVC Web Application.

Drupal函数之一从Web服务获取一些数据。并将其转换为JS数组,如下所示:

One of the Drupal functions gets some data from a web service and converts it to a JS Array, as follows:

foreach ($xml_result->JobList->JobDetail as $job_detail) {
//  dsm((array)$job_detail); 
$open_job_details[] = array("east"=>(string)$job_detail->Easting,"north"=>(string)$job_detail->Northing, "duedate"=>(string)$job_detail->openDate);
}
//dsm($open_job_details); 
$open_jobs_data = json_encode($open_job_details);
drupal_add_js(array('open_jobs' => array('open_newjobs' => $open_jobs_data)), 'setting');

在Javascript文件中,使用来访问它;

In the Javascript file, it is accessed using;

var openJobsData = JSON.parse(Drupal.settings.open_jobs.open_newjobs);

是否有一种简单的方法来访问.NET中JS文件中的服务器端变量?我可以调用Web服务并从XML文件中获取相关数据,但不确定如何在JS文件中访问它。

Is there a simple way to access a server side variable in the JS file in .NET? I can call the web service and get the relevant data from the XML file but not sure how to access it in the JS file.

谢谢

推荐答案

您可以使用强类型视图创建cshtml页面

You can use Strongly Typed view to create cshtml page


  • 如果要访问JSON对象

  • if you want to access JSON object

View1.cshtml
@model mvcApplication1.Models.model1
@ {
var serializer =新的
System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = int.MaxValue;
var jsonModel = serializer.Serialize(Model);
}
var JsonData = @ Html.Raw(jsonModel); //声明一个javascript变量并使用它

View1.cshtml @model mvcApplication1.Models.model1 @{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); serializer.MaxJsonLength = int.MaxValue; var jsonModel = serializer.Serialize(Model); } var JsonData = @Html.Raw(jsonModel); // declare a javascript variable and use it

如果要访问cshtml页面
上的服务器变量,只需使用 @ 在获取值后访问服务器端变量
,可以在另一个js文件中使用javascript变量

if you want to access server variable at cshtml page just use @ to access server-side variables after getting the value you can use javascript variable in another js file

在外部声明您的javascript变量
$(document).ready(function()
{}

Declare your javascript variable outside $(document).ready(function() {}

或在使用变量之前

您可以在Javascript文件中使用该变量。

you can use that variable in Javascript file.

这篇关于在JavaScript中访问MVC服务器端变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆