【问题标题】:Viewmodel returning no dataViewmodel 不返回数据
【发布时间】:2017-05-05 22:36:06
【问题描述】:

一直在尝试遵循一些在线示例,目的是从为我的视图使用模型转向使用视图模型。

我有一个名为“Property”的模型,并且我创建了一个名为“PropertyIndexViewModel”的 ViewModel,我的视图现在正在引用它。

我的控制器动作是:

// 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);
}

我的视图没有抛出任何错误,但也没有从模型返回预期数据?

【问题讨论】:

  • 您的操作方法返回PropertyIndexViewModel 对象。如果没有通过传递对象的数据来调用该方法,则viewModel 对象将为空。
  • 您正在混合使用 MVVM 和 MVC。不要那样做,你只是不必要地给自己带来麻烦。您希望在 ASP.NET MVC 应用程序中使用 MVVM 的唯一时间是在客户端中(使用 angular 或 knockout 或类似的)。出于某种原因,它被称为 ASP.NET MVC 而不是 ASP.NET MVVM。

标签: c# asp.net-mvc mvvm viewmodel


【解决方案1】:

你必须初始化视图模型,用属性模型数据填充它并返回它。

// 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);
}

在您看来,您必须指定模型:

@model PropertyIndexViewModel

【讨论】:

  • 谢谢,效果很好。我想我已经假设映射是自动的。我可以想象当您必须映射大型视图模型时它会变得非常复杂!无论如何,再次感谢您的努力
  • 如果您的视图显示模型是自动的,当然,在复杂场景中构建视图模型可能不会那么快速和容易。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-18
  • 1970-01-01
相关资源
最近更新 更多