RProgrammer
RProgrammer

Reputation: 47

pass object from controller to view in asp.net MVC and call object methods in view

I create an object of class in controller and I pass it by viewData,viewBag,viewModel. I want to call object methods in view and display the results in it I write call methods in script in view file, but the code not executed , I dont know where is the error so I try the following code

my code in controller

public ActionResult Categorized()

{ var x=new PICWeb.Models.MobileClass(); return View(x); }

and my code in view file

<script type="text/javascript"> var test = model.getCategories(); </script> 

and tried the following code

public ActionResult Categorized()

{ var x=new PICWeb.Models.MobileClass(); ViewData["ser"]=x; ViewBag.ser=x; return View(); }

and in view

 <script type="text/javascript">

    var [email protected];

    var test2=@viewData["ser"];

    var res=test1.getCategories();

    var res2=test2.getCategories()

    </script> 

                                                                                   so where is the problem , can you help me

Upvotes: 0

Views: 2179

Answers (1)

Francisco Afonso
Francisco Afonso

Reputation: 247

I really advice you to follow this tutorials before starting to program something from scratch in MVC:

http://www.w3schools.com/aspnet/mvc_intro.asp

See how you can simply pass the model to a strongly typed view and access its properties and methods.

@EDIT: You're trying to run a model method in a javascript function created on a view. That's the problem. If you really want that content run the method before and pass the result to the view or you could and should use jquery ajax calls to run async method calls.

Upvotes: 1

Related Questions