0

How can I access my viewmodel from my view? my code is as follows:-,

I have two models (using entity framework) which have a view model of:-

 public class ViewModelStory
{
    public IEnumerable<tbl_GCB_NewsItem> GCB_NewsItem { get; set; }
    public IEnumerable<tbl_GCB_ItemComment> comemnts { get; set; }

}

My contoller populates the models by:-

        ViewModelStory.GCB_NewsItem = (from i in db.tbl_GCB_NewsItem
                    where i.intItemIdentifier.ToString() == StoryId
                    select i).SingleOrDefault();

        ViewModelStory.comemnts = (from i in db.tbl_GCB_ItemComment
                                       where i.intItemIdentifier.ToString() == StoryId
                                       select i).ToList<tbl_GCB_ItemComment>();

I return the model by

      return PartialView("NewsStory", ViewModelStory);

then in my view I have the following declaration

@model ViewModelStory
@using GCBSMVC.Models

To access my model I have tried various from Linq to and directly querying the model, but nothing seems to work:- Html.DisplayFor(m =>m.GCB_NewsItem. .... ViewModelStory.GCB_NewsItem.strItemCategory Html.Raw(System.Web.HttpUtility.HtmlDecode(ViewModelStory.GCB_NewsItem.strItemHeadline))

3
  • What does the return value of your controller action look like? Do you populate the view to return correctly, e.g return View("myView", myModel)? Commented Sep 10, 2014 at 14:19
  • I return it by : return PartialView("NewsStory", ViewModelStory); i shall also update the question forgot to add this bit. Commented Sep 10, 2014 at 15:38
  • I m afraid but you can't set ViewModelStory.GCB_NewsItem properties this way. Please make an object and then set properties. if your object has same name as class, please change it and try. Commented Sep 11, 2014 at 8:09

1 Answer 1

1

You are passing the type of you model class instead of the actual class. Try this:

var model = new ViewModelStory();
model.GCB_NewsItem = (from i in db.tbl_GCB_NewsItem
                    where i.intItemIdentifier.ToString() == StoryId
                    select i).SingleOrDefault();

model.comemnts = (from i in db.tbl_GCB_ItemComment
                                       where i.intItemIdentifier.ToString() == StoryId
                                       select i).ToList<tbl_GCB_ItemComment>();

return PartialView("NewsStory", model);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.