25

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 this

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.

Thanks

Parminder
  • 3,088
  • 6
  • 37
  • 61
  • are you trying to make the model and it's properties available to javascript? or are you trying to make a single string property from the model available to your script? – Jason Nov 16 '11 at 02:25

5 Answers5

39

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.

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 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>
Community
  • 1
  • 1
Tommy
  • 39,592
  • 10
  • 90
  • 121
  • 1
    i need to pass the whole object, passing property is not an issue at all. – Parminder Nov 16 '11 at 02:08
  • i didn't mean to post that last comment, i intended to create a new answer once i remembered i couldn't format code down here. – Jason Nov 16 '11 at 02:09
  • Tommy, you are not getting the point, razor syntax is not issue. the issue is how to convert the Object to string. – Parminder Nov 16 '11 at 02:13
  • @Parminder - I was getting the point until you updated your question :) Look for another edit – Tommy Nov 16 '11 at 02:16
  • Tommy, I need whole object converted, not just one property. – Parminder Nov 16 '11 at 02:20
  • The code example above could be refactored in the controller method, but I hope this helps give you a push in the right direction. – Tommy Nov 16 '11 at 02:22
  • @Jason - no sweat, I noticed the syntax error in my own answer once I posted it :) – Tommy Nov 16 '11 at 02:22
  • @Parminder: Is that comment in reference to Edit 2? That function above converts the entire 'options' object into JSON notation. We are using a single property on the ViewModel to hold the resulting JSON string. We are also still passing the options class as part of the view model in case you need to use it in other parts of the view outside of a JS function. – Tommy Nov 16 '11 at 02:29
  • @Jason fantastic. Thats great. Thanks to Daniel A White as well. – Parminder Nov 16 '11 at 02:57
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/5033/discussion-between-parminder-and-tommy) – Parminder Nov 16 '11 at 04:02
  • FYI, I was using `JavaScriptSerializer`, and I also tried `Json.Encode()`, but I was having issues with dates showing up like `/Date(286769410010)/`. [This answer](http://stackoverflow.com/a/17070083/259457) suggested using Json.NET instead, and that solved my issue. Just a heads up in case anyone else is having the same trouble I did. – Travesty3 Feb 08 '16 at 21:36
18

Try this:

<script type="text/javascript">
    var obj= @Html.Raw(Json.Encode(Model));
    function dosomething(obj){}
</script>
FelixSFD
  • 6,052
  • 10
  • 43
  • 117
sanjeewa
  • 564
  • 1
  • 5
  • 17
  • 3
    It's better to include some context/explanation with code as this makes the answer more useful for the OP and for future readers. – EJoshuaS - Stand with Ukraine Jan 05 '17 at 06:07
  • @PrakharTrivedi A code-only answer might not be a good one, but it's still an answer. I would recommend you this post about the LQPRQ: [You're doing it wrong: A plea for sanity in the Low Quality Posts queue](http://meta.stackoverflow.com/questions/287563/youre-doing-it-wrong-a-plea-for-sanity-in-the-low-quality-posts-queue) – FelixSFD Jan 05 '17 at 10:43
  • 1
    it worked for me, and what i have learned is: Json.Encode will converts a data object to a string that is in the JavaScript Object Notation (JSON) format. and Html.Raw will just give you a markup which is not Html encoded – Atta H. Feb 08 '18 at 16:17
  • In above example "var obj= @Html.Raw(Json.Encode(Model));" obj will contain the object similar to C# object, and you can play with it I use it and get this (where I was using it) https://www.screencast.com/t/TiJxKVK06Xo – Atta H. Feb 08 '18 at 16:24
  • 1
    While unintuitive, using JSON.parse will be faster here. For example, `var obj= JSON.parse('@Html.Raw(Json.Encode(Model))');` – Onosa Dec 09 '19 at 21:18
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>
ZoharAdar
  • 474
  • 1
  • 7
  • 19
1

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:

<script type="text/javascript">
  dosomething("this model has been stringified!");
</script>
Jason
  • 15,915
  • 3
  • 48
  • 72
  • my mistake but stringify is not what u see here http://msdn.microsoft.com/en-us/library/cc836459%28VS.85%29.aspx , I have edit the question. have a look. – Parminder Nov 16 '11 at 02:10
  • 2
    it doesn't matter what function you call on the model. the point is the model is executed on the server, and the javascript on the client. everything flows from the understanding of where the code is executing. – Jason Nov 16 '11 at 02:15
1

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:

public class Chat : Hub {
    public void Distribute(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.

JTew
  • 3,149
  • 3
  • 31
  • 39
  • 10
    You certainly have a very blunt manner when trying to get answers from others. You title states you were looking for passing C# objects to a html view, SignalR does this. SignalR is an alternate way of achieving what you asked for and provides lower bandwidth consumption than multiple sends that include full http headers. – JTew Nov 16 '11 at 07:01