Asp.net mvc 将 C# 对象传递给 Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8145716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Asp.net mvc passing a C# object to Javascript
提问by Parminder
I have c# class say options more like AjaxOptions.
我有 c# 类说选项更像 AjaxOptions。
public class options
{
public string Url {get;set;}
public string httpMethod {get;set}
}
and a javascript function like this
和这样的 javascript 函数
function dosomething(obj)
{
if (obj.Url!="" and obj.HttpMethod=="something")
loadsomething();
}
Now in my Controller action
现在在我的控制器操作中
public class mycontroller : controller
{
public ActionResult WhatToDo()
{
options obj = new options{Url="someurl"};
return PartialView(obj);
}
}
in my view I need this object kind of string which i should be able to pass to my method.
在我看来,我需要这种对象类型的字符串,我应该能够将其传递给我的方法。
@model options
<script>
dosomething(@model.SomeFunctionToConverToString())
</script>
So I need this SomeFunctionToConverToString method which i will convert this object to string.
所以我需要这个 SomeFunctionToConverToString 方法,我会将这个对象转换为字符串。
Thanks
谢谢
回答by Tommy
You should be able to use it like you would any other output of a model property in your view. Just reference the property that you want to pass in the JS function.
您应该能够像使用视图中模型属性的任何其他输出一样使用它。只需引用您要在 JS 函数中传递的属性即可。
@model options
<script>
dosomething('@(model.Url)');
</script>
See this postfor more information on using Razor inside of JS
有关在 JS 中使用 Razor 的更多信息,请参阅此帖子
EDIT- Something that might catch you is that if your URL get's broken from the HTML encoding that Razor does using the above, you can use the @Html.Raw()
function which will pass the Url property without HTML encoding it.
编辑- 可能会引起您注意的是,如果您的 URL 与 Razor 使用上述内容所做的 HTML 编码断开,您可以使用@Html.Raw()
将传递 Url 属性而不对其进行 HTML 编码的函数。
<script>
dosomething('@Html.Raw(model.Url)');
</script>
EDIT 2- And another SO postto the rescue! You are going to most likely want to convert your model to JSON in order to use in a Javascript function. So...in order to do that - you will need something in your view model to handle a JSON object.
编辑 2-另一个 SO 帖子来救援!您很可能希望将模型转换为 JSON,以便在 Javascript 函数中使用。所以......为了做到这一点 - 你需要在你的视图模型中使用一些东西来处理 JSON 对象。
public class optionsViewModel
{
public options Options{get;set;}
public string JsonData{get;set;}
}
and in your controller:
并在您的控制器中:
public class mycontroller : controller
{
public ActionResult WhatToDo()
{
options obj = new options{Url="someurl"};
var myViewModel = new optionsViewModel;
myViewModel.options = obj;
var serializer = new JavaScriptSerializer();
myViewModel.JsonData = serializer.Serialize(data);
return PartialView(myViewModel);
}
}
And finally the view:
最后是视图:
@model optionsViewModel
<script>
dosomething('@model.JsonData')
</script>
Using this method, then your function will work as expected:
使用此方法,您的功能将按预期工作:
function dosomething(obj)
{
if (obj.Url!="" and obj.HttpMethod=="something")
loadsomething();
}
EDIT 3Potentially the simplest way yet? Same premise as edit 2, however this is using the View to JsonEncode the model. There are probably some good arguments on either side whether this should be done in the view, controller, or repository/service layer. However, for doing the conversion in the view...
编辑 3可能是最简单的方法吗?与编辑 2 相同的前提,但是这是使用视图对模型进行 JsonEncode。无论这应该在视图、控制器还是存储库/服务层中完成,双方可能都有一些很好的论据。但是,为了在视图中进行转换......
@model options
<script>
dosomething('@Html.Raw(Json.Encode(Model))');
</script>
回答by sanjeewa
Try this:
尝试这个:
<script type="text/javascript">
var obj= @Html.Raw(Json.Encode(Model));
function dosomething(obj){}
</script>
回答by ZoharAdar
That's work for me
这对我有用
Client side:
客户端:
function GoWild(jsonData)
{
alert(jsonData);
}
Alert print :
警报打印:
{"wildDetails":{"Name":"Al","Id":1}}
MVC Razor Side:
MVC 剃刀面:
@{var serializer new System.Web.Script.Serialization.JavaScriptSerializer();}
<div onclick="GoWild('@serializer.Serialize(Model.wildDetails)')"> Serialize It </div>
回答by Jason
there is also a syntax error
还有一个语法错误
<script type="text/javascript">
dosomething("@Model.Stringify()");
</script>
note the quotes around @Model.Stringify() are for javascript, so the emitted HTML will be:
请注意 @Model.Stringify() 周围的引号是针对 javascript 的,因此发出的 HTML 将是:
<script type="text/javascript">
dosomething("this model has been stringified!");
</script>
回答by JTew
I would recommend you have a look at SignalR, it allows for server triggered javascript callbacks.
我建议你看看SignalR,它允许服务器触发的 javascript 回调。
See Scott H site for details: http://www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx
有关详细信息,请参阅 Scott H 站点:http: //www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx
In summary thou ...
总之你...
Javascript Client:
Javascript客户端:
var chat = $.connection.chat;
chat.name = prompt("What's your name?", "");
chat.receive = function(name, message){
$("#messages").append("
"+name+": "+message);
}
$("#send-button").click(function(){
chat.distribute($("#text-input").val());
});
Server:
服务器:
public class Chat : Hub {
public void Distribute(string message) {
Clients.receive(Caller.name, message);
}
}
So .. Clients.receivein C# ends up triggering the chat.receivefunction in javascript.
所以.. Clients.receive在C#中结束了触发chat.receive在javascript函数。
It's also available via NuGet.
它也可以通过 NuGet 获得。