Parminder Parminder - 15 days ago 7
Javascript Question

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 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

Answer

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>
Comments