Gavin5511
Gavin5511

Reputation: 791

Viewmodel returning no data

Been trying to follow some online examples, with the aim of moving away from using models for my views, to using viewmodels.

I have a model called 'Property' and i have created a ViewModel called 'PropertyIndexViewModel', which my view is now referencing.

My controller action is:

// GET: Property ***TEST***
public async Task<ActionResult> Index1(int? id, PropertyIndexViewModel viewModel)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Property property = await db.Property.FindAsync(id);
    if (property == null)
    {
        return HttpNotFound();
    }
    return View(viewModel);
}

My view isn't throwing any errors, but it's also not returning the expected data from the model?

Upvotes: 0

Views: 706

Answers (1)

Darion Badlydone
Darion Badlydone

Reputation: 947

You have to initialize the view model, fill it with the Property model data and return it.

// GET: Property ***TEST***
public async Task<ActionResult> Index1(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Property property = await db.Property.FindAsync(id);
    if (property == null)
    {
        return HttpNotFound();
    }

    var viewModel = new PropertyIndexViewModel {
        Prop1 = property.Prop1
        // your stuff
    };

    return View(viewModel);
}

In your view you have to specify the model:

@model PropertyIndexViewModel

Upvotes: 2

Related Questions