简体   繁体   English

我可以在局部视图中使用Javascript(带有@语法)吗?

[英]Can I use Javascript (with @ syntax) from partial into the main view?

Apologies if I'm using the wrong terminology, I'm fairly new to this technology. 抱歉,如果我使用了错误的术语,那么我对这项技术还是陌生的。

I have a view which we'll call MainView.cshtml: 我有一个称为MainView.cshtml的视图:

<div>
  @RenderPartial("_Partial");
</div>

<script type="text/javascript">
 $(document).ready(function() {
    someFunctionDefinedIn_Partial();
 }
</script>

The _Partial view has javascript that defines a function (in this case someFunctionDefinedIn_Partial . _Partial视图具有定义函数的javascript(在本例中为someFunctionDefinedIn_Partial

function someFunctionDefinedIn_Partial()
{
  // This uses the "@" syntax to access C# variables, which can be done in .cshtml
  alert("Hello. This variable is from C#: @ClassInCSharp.Variable");
}

When I run the code above I'm told in the chrome console that the function someFunctionDefinedIn_Partial doesn't exist. 当我运行上面的代码时,我在chrome控制台中被告知该函数someFunctionDefinedIn_Partial不存在。 I'm guessing this is because javascript in a partial doesn't make its way out to the container. 我猜这是因为部分Javascript无法将其导出到容器中。

I looked around a bit and found that I can extract the javascript to its own .js file and reference that as shown in this SO post: How to render JavaScript into MasterLayout section from partial view? 我四处张望,发现可以将javascript提取到其自己的.js文件中,并引用此SO文章中所示的内容: 如何从局部视图将JavaScript渲染到MasterLayout部分中?

However, the post above suggests extracting javascript into its own separate file .js. 但是,以上文章建议将javascript提取到其自己的单独文件.js中。 If I do this, then I am using "raw" javascript, so I can't use the @ notation to reference variables from my C#. 如果执行此操作,则说明我使用的是“原始” JavaScript,因此无法使用@表示法引用C#中的变量。

Is it possible to somehow include javascript in my MainView.cshtml which also has access to the @ syntax so I can use C# methods/variables? 是否可以以某种方式在我的MainView.cshtml中包含javascript,它也可以访问@语法,所以我可以使用C#方法/变量? If not, is it possible to create an external javascript file, but have it be a .cshtml file so I can use the "@" syntax? 如果没有,是否可以创建一个外部javascript文件,但是它是否为.cshtml文件,因此我可以使用“ @”语法?

Can I use Javascript (with @ syntax) from partial into the main view? 我可以在局部视图中使用Javascript(带有@语法)吗?

Yes, but the order of javascript operations is very important. 是的,但是javascript操作的顺序非常重要。 Strictly speaking, the following javascript code should error out: 严格来说,以下javascript代码应该会出错:

console.log(myvariable);
var myvariable = "hello world!";

I'm using a variable before it's defined. 我正在使用一个变量,然后再定义它。 That is the similar problem you are having. 那就是您遇到的类似问题。

Would I recommend using Javascript directly inside a view? 我是否建议直接在视图内使用Javascript?

Definitely almost exclusively never . 绝对几乎绝对不会 The way most javascript/css/html is written today is tightly coupled enough. 当今大多数javascript / css / html的编写方式都紧密结合在一起。 Adding a coupling to C# seems like a giant code smell . 在C#中添加耦合似乎是一种巨大的代码味道 My personal preference is to add data to html elements and have the javascript only coupled to my html. 我个人的喜好是将数据添加到html元素,并将javascript仅耦合到我的html。 So instead of : 所以代替:

<script>
var myIds = [@(string.Join(Model.People.Select(p => Id.ToString().ToArray(), ",")];
</script>

Which is just insanely ugly and hard to debug, I apply my values to the html presentation that is representing my object: 这真是丑陋且难以调试,我将我的值应用于代表我的对象的html演示文稿:

<div data-id="@model.Id" class="person">
  Person Name: @Html.DisplayFor(m => m.name)
</div>

<script>
var myIds = [];
$('.person').each((i,p) => myIds.push($(p).data("Id"));
</script>

Now I can't really make a mistake about making sure the Id's in my array are the same ones on the page, everything is encapsulated together. 现在,对于确保数组中的ID与页面上的ID相同,所有内容都封装在一起,我真的不会犯错。

The other code smell is using @() methods in a view for logic. 另一个代码气味是在逻辑视图中使用@()方法。 For example, I see a lot of: 例如,我看到很多:

@foreach(var person in Model.persons) 
{
  if (person.Age >= 21)
  {
    <div>Adult</div>
  }
  else
  {
    <div>Child</div>
  }
}

To me, that is logic in a view. 在我看来,这是逻辑。 My definition of a ViewModel is a model that represents all the necessary data-points (even those derived from logic). 我对ViewModel的定义是一个表示所有必要数据点(甚至是从逻辑派生的数据点)的模型。 So I would do something like: 所以我会做类似的事情:

public class PersonVM
{
  public DateTime BornOn { get; set; }
  public bool IsAdult { get { return /*BornOnLogic*/; } ]
}

So in my view, I don't understand why anyone would need to use any C# directly within Javascript. 因此,在我看来,我不明白为什么有人需要直接在Javascript中使用任何C#。

I would also recommend reading Philip Walton's (Google Engineer) -Decoupling Your HTML, CSS, and JavaScript . 我还建议您阅读Philip Walton的(Google工程师)-分离HTML,CSS和JavaScript

I don't recommend you to include JS in a Partial view, as it can be added many times in a given view. 我不建议您在局部视图中包含JS,因为它可以在给定视图中多次添加。 Take a look at link 看一下链接

I suggest you to move the partials JS to the main view. 我建议您将局部JS移至主视图。

UPDATE UPDATE

If you don't have any other option, consider that Razor cannot be used in plain JS: Link 如果您没有其他选择,请考虑不能在普通JS中使用Razor: 链接

What you can do is to extract the C# values needed in your JS and send them when invoking the JS. 您可以做的是提取JS中所需的C#值,并在调用JS时将其发送。 So you could have: 因此,您可以:

function someFunctionDefinedIn_Partial(variableValue)
{
  // This uses the "@" syntax to access C# variables, which can be done in .cshtml
  alert("Hello. This variable is from C#: " + variableValue);
}

And invoke it from the partial view: 并从局部视图调用它:

someFunctionDefinedIn_Partial(@ClassInCSharp.Variable);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM