简体   繁体   中英

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.

You cannot use a javascript variable in your c# code. But the reverse is possible. However in this scenario you must use ajax itself to load your partial view.

What you can try is ..

1) Create a ActionResult which will return a partial view. (Make sure you set the ActionResult name same as your partial view name, This is only to reduce confusion in your code.)

2) Then in jquery hit this 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.

You can use JsonResult type :

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

Jquery call to get that Json

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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