Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
    
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 2:25

4 Answers 4

up vote 6 down vote accepted

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>
share|improve this answer
    
i need to pass the whole object, passing property is not an issue at all. –  Parminder Nov 16 '11 at 2: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 2: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 2:13
    
@Parminder - I was getting the point until you updated your question :) Look for another edit –  Tommy Nov 16 '11 at 2:16
    
Tommy, I need whole object converted, not just one property. –  Parminder Nov 16 '11 at 2:20

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>
share|improve this answer
    
my mistake but stringify is not what u see here msdn.microsoft.com/en-us/library/cc836459%28VS.85%29.aspx , I have edit the question. have a look. –  Parminder Nov 16 '11 at 2:10
1  
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 2:15

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.

share|improve this answer
    
you need to read the question properly. –  Parminder Nov 16 '11 at 2:19
4  
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 7:01

You can use JavaScriptSerializer.

share|improve this answer
    
Thanks Daniel, it helped. –  Parminder Nov 16 '11 at 2:54
    
@Parminder - no problem. –  Daniel A. White Nov 16 '11 at 2:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.