Skip to content Skip to sidebar Skip to footer

Asp.net Mvc Passing A C# Object To Javascript

I have c# class say options more like AjaxOptions. public class options { public string Url {get;set;} public string httpMethod {get;set} } and a javascript function like th

Solution 1:

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.

@model options

<script>dosomething('@(model.Url)');
</script>

See this post for more information on using Razor inside of JS

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.

<script>dosomething('@Html.Raw(model.Url)');
</script>

EDIT 2 - And another SO post to 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.

publicclassoptionsViewModel
{
   public options Options{get;set;}
   publicstring JsonData{get;set;}
}

and in your controller:

publicclassmycontroller : 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 3 Potentially 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...

@model options

<script>dosomething('@Html.Raw(Json.Encode(Model))');
</script>

Solution 2:

Try this:

<scripttype="text/javascript">var obj= @Html.Raw(Json.Encode(Model));
    functiondosomething(obj){}
</script>

Solution 3:

That's work for me

Client side:

function GoWild(jsonData)
{
    alert(jsonData);
}

Alert print :

{"wildDetails":{"Name":"Al","Id":1}}

MVC Razor Side:

 @{var serializer new System.Web.Script.Serialization.JavaScriptSerializer();}
<div onclick="GoWild('@serializer.Serialize(Model.wildDetails)')"> Serialize It </div>

Solution 4:

there is also a syntax error

<scripttype="text/javascript">dosomething("@Model.Stringify()");
</script>

note the quotes around @Model.Stringify() are for javascript, so the emitted HTML will be:

<scripttype="text/javascript">dosomething("this model has been stringified!");
</script>

Solution 5:

I would recommend you have a look at SignalR, it allows for server triggered javascript callbacks.

See Scott H site for details: http://www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx

In summary thou ...

Javascript Client:

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:

publicclassChat : Hub {
    publicvoidDistribute(string message) {
        Clients.receive(Caller.name, message);
    }
}

So .. Clients.receive in C# ends up triggering the chat.receive function in javascript.

It's also available via NuGet.

Post a Comment for "Asp.net Mvc Passing A C# Object To Javascript"