简体   繁体   English

如何将JavaScript变量传递给Razor C#代码?

[英]How to pass a javascript variable to Razor c# code?

@{
    var Countries=Model.FirstOrDefault(x=>x.Id==**JavaScriptVariable**);

    @Html.Partial("Countries", Countries)

}

I know its possible using ajax call, but how to assign the json result returned from server side to Razor c# code, I should either place the value in the model or ViewBag before returning the view but i dont know how to code it. 我知道使用ajax调用是可能的,但是如何将从服务器端返回的json结果分配给Razor c#代码,我应该在返回视图之前将值放在模型或ViewBag中,但是我不知道如何编码。

You cannot use a javascript variable in your c# code. 您不能在C#代码中使用javascript变量。 But the reverse is possible. 但是相反的可能。 However in this scenario you must use ajax itself to load your partial view. 但是,在这种情况下,您必须使用ajax本身来加载部分视图。

What you can try is .. 你可以尝试的是..

1) Create a ActionResult which will return a partial view. 1)创建一个ActionResult,它将返回部分视图。 (Make sure you set the ActionResult name same as your partial view name, This is only to reduce confusion in your code.) (确保将ActionResult名称设置为与部分视图名称相同,这只是为了减少代码中的混乱。)

2) Then in jquery hit this ActionResult. 2)然后在jquery中点击此ActionResult。

something like.. 就像是..

 $.get('/YourController/'+ JavaScriptVariable +'/',function(result){
    //you got the partial view here...
    $('#yourDiv').append(result);
 });

You should assign data in your controller using the following line: 您应该使用以下行在控制器中分配数据:

    ViewBag.TestVariable = "Test string";

In the view you can access this data like below: 在视图中,您可以按如下方式访问此数据:

    @ViewBag.TestVariable 

In your case I'd move the logic that assigns data to the variable 'Countries' to the controller and then use a ViewBag to store that data and access it from the View. 在您的情况下,我将将为数据“ Countries”分配数据的逻辑移至控制器,然后使用ViewBag存储该数据并从View中访问它。

You can use JsonResult type : 您可以使用JsonResult类型:

public JsonResult fnname()
    {
        // Do something
        return Json(youJson , JsonRequestBehavior.AllowGet);
    }

Jquery call to get that Json jQuery调用以获取该Json

 $(document).ready(function() {
   $.post("/controllername/fnname", { }, function (result) {
      alert(result);
   }, "json");
 });

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

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