实施ASP.NET MVC 3接口模型绑定(与视图模型)模型、视图、绑定、接口

由网友(炸学校)分享简介:我刚开始学习ASP.NET MVC 3,我如何,我可以实现类似什么是显示在这个环节有点糊涂了:HTTP://www.codethinked.com /易和安全模型结合功能于ASPNET-MVC 为什么我很困惑很可能是基于我在这个问题的无知。在上面的链接页面上的例子,我看到贾斯汀正在使用视图模型直接包含他的人对象的属性...

我刚开始学习ASP.NET MVC 3,我如何,我可以实现类似什么是显示在这个环节有点糊涂了:

HTTP://www.codethinked.com /易和安全模型结合功能于ASPNET-MVC

为什么我很困惑很可能是基于我在这个问题的无知。在上面的链接页面上的例子,我看到贾斯汀正在使用视图模型直接包含他的人对象的属性。

我想要做的是类似的,但我希望有一个视图模型实际上包含了域类,这是我公司的情况下,而不是人。我在公司类本身实现了视图模型子集的意见(例如IEditCompanyAsUser)。

我已经试过到目前为止看起来像这样:

 公共类公司:IValidatableObject,ICompanyUpdateAsUser
{
    [键]
    [ScaffoldColumn(假)]
    公共虚拟INT CompanyID {获得;组; }

    [需要]
    公共虚拟布尔主动{获得;组; }

    [需要]
    公共虚拟字符串名称{;组; }

    [需要]
    公共虚拟字符串电话{获得;组; }

    //包含了一些更多的成员如下
 }
 

通过包含的属性ICompanyUpdateAsUser我想我的控制器的编辑方法更新:

 公共接口ICompanyUpdateAsUser
{
    布尔主动{获得;组; }
    字符串名称{;组; }
    串电话{获得;组; }
}
 
详解ASP.NET MVC 中的 View 模型

和看起来像这样一个ViewModel类:

 公共类CompanyViewModel
{
    上市公司的公司;
    //将在将来增加更多的成员
}
 

我想不通的是如何正确$ C C控制器$。我的控制器目前看起来像这样:

  ///<总结>
    /// POST:/公司/编辑/ 5
    ///< /总结>
    [HttpPost]
    公众的ActionResult编辑([绑定(preFIX =公司)公司模式)
    {
        VAR公司= _companyService.GetCompany(model.CompanyID);

        如果(公司== NULL)
            返回RedirectToAction(指数);

        如果(ModelState.IsValid)
        {
            如果(TryUpdateModel< ICompanyUpdateAsUser>(公司))
            {
                _companyService.SaveCompany();
                返回RedirectToAction(详细信息,新{companyId = model.CompanyID});
            }
        }

        返回查看(模型);
    }
 

我知道的东西是绝对错误与我的控制器code,但我想不出什么成分,我需要用它来实现这样的模式?我是否需要使用自定义模型联?我是否需要使用ASP.NET MVC3的其他一些功能来实现该模式?

任何意见将是极大的AP preciated。

谢谢!

*的的修改的*

我需要做的是编辑视图后回一个公司的对象,然后在post'ed公司(根据传递给TryUpdateModel接口上的属性)的值更新从数据库中的对象。一切似乎是工作(验证等),但TryUpdateModel(公司)似乎并不奏效,但评估为true。当我通过code与调试步骤,该公司目标从DB拉简直是永远不会更新。

在多一点读书,我已经确定了TryUpdateModel方法更新从方法的IValueProvider该项目通过了。我该如何关联的传递公司模式与IValueProvider的方法?

解决方案

我结束了首先使一对夫妇modifications..in我的问题的解决该问题,我的控制器无法使用我创造的ViewModel类。有一次,我修改了控制器看起来像这样:

  ///<总结>
    /// POST:/公司/编辑/ 5
    ///< /总结>
    [HttpPost]
    公众的ActionResult编辑(CompanyViewModel视图模型)
    {
        VAR公司= _companyService.GetCompany(viewModel.Company.CompanyID);

        如果(公司== NULL)
            返回RedirectToAction(指数);

        如果(ModelState.IsValid)
        {
            如果(TryUpdateModel< ICompanyUpdateAsUser>(公司,「本公司」))
            {
                _companyService.SaveCompany();
                返回RedirectToAction(详细信息,新{companyId = viewModel.Company.CompanyID});
            }
        }

        返回视图(视图模型);
    }
 

我发现,一切似乎能正常工作,但如上面TryUpdateModel评论说根本就没有工作,虽然返回true!

通过吨堆栈溢出和放大器的筛选后,其他论坛的帖子,我最终发现,TryUpdateModel不上的字段,只有属性的作用。为了得到它正常工作,我不得不改变我的视图模型看起来像这样:

 公共类CompanyViewModel
{
    上市公司公司{获得;组; }

    公共CompanyViewModel(公司公司)
    {
        公司=公司;
    }

    公共CompanyViewModel()
    {
        公司=新的公司();
    }
 }
 

这样一个愚蠢的错误,但我觉得这一点是由许多我已经阅读了模型绑定教程远远忽略了。

希望这个答案会节约一些时间。

I just learning ASP.NET MVC 3 and I'm a bit confused on how I can implement something like what is shown in this link:

http://www.codethinked.com/easy-and-safe-model-binding-in-aspnet-mvc

Why I'm confused is most likely based on my ignorance in the subject. In the example on the page linked above, I see Justin is using a ViewModel that directly contains properties of his "Person" object.

What I want to do is similar, but I want to have a ViewModel actually contain the domain class, which is in my case Company, rather than Person. I'm having the Company class itself implement the ViewModel subset views (ex. IEditCompanyAsUser).

What I've tried so far looks something like so:

public class Company : IValidatableObject, ICompanyUpdateAsUser
{
    [Key]
    [ScaffoldColumn(false)]
    public virtual int CompanyID { get; set; }

    [Required]
    public virtual Boolean Active { get; set; }

    [Required]
    public virtual string Name { get; set; }

    [Required]
    public virtual string Phone { get; set; }

    // Containing some more members below
 }

With ICompanyUpdateAsUser containing the properties I would like my controller's Edit method to update:

public interface ICompanyUpdateAsUser
{
    bool Active { get; set; }
    string Name { get; set; }
    string Phone { get; set; }  
}

And a ViewModel class that looks like so:

public class CompanyViewModel
{
    public Company Company;
    // Will be adding more members in the future
}

What I can't figure out is how to properly code the controller. My controller currently looks like so:

    /// <summary>
    /// POST: /Company/Edit/5
    /// </summary>
    [HttpPost]
    public ActionResult Edit([Bind(Prefix="Company")]Company model)
    {
        var company = _companyService.GetCompany(model.CompanyID);

        if (company == null)
            return RedirectToAction("Index");

        if (ModelState.IsValid)
        {
            if (TryUpdateModel<ICompanyUpdateAsUser>(company))
            {
                _companyService.SaveCompany();
                return RedirectToAction("Details", new { companyId = model.CompanyID });
            }
        }

        return View(model);
    }

I know something is absolutely wrong with my controller code but I can't figure out what components I need to use to implement such a pattern? Do I need to use a custom model binder? Do I need to use some other feature of ASP.NET MVC3 to implement the pattern?

Any advice would be greatly appreciated.

Thanks!

*EDIT*

What I need to do is have the Edit view post back a "Company" object, then update the object from the database with the values on the post'ed Company (according to the properties on the interface passed to TryUpdateModel). Everything appears to be working (validation, etc.), but the TryUpdateModel(company) does not seem to be working, though evaluating to true. When I step through the code with a debugger, the Company object pulled from the DB is simply never updated.

After a bit more reading, I've determined the TryUpdateModel method updates the passed item from the method's IValueProvider. How can I associated the passed in "Company model" with the IValueProvider for the method?

解决方案

I ended up resolving the issue by first making a couple of modifications..in my question, my controller failed to use the ViewModel class I had created. Once I modified the controller to look like so:

 /// <summary>
    /// POST: /Company/Edit/5
    /// </summary>
    [HttpPost]
    public ActionResult Edit(CompanyViewModel viewModel)
    {
        var company = _companyService.GetCompany(viewModel.Company.CompanyID);

        if (company == null)
            return RedirectToAction("Index");

        if (ModelState.IsValid)
        {
            if (TryUpdateModel<ICompanyUpdateAsUser>(company, "Company"))
            {
                _companyService.SaveCompany();
                return RedirectToAction("Details", new { companyId = viewModel.Company.CompanyID });
            }
        }

        return View(viewModel);
    }

I found that everything appeared to be working properly, but as stated in the comments above TryUpdateModel simply DID NOT work, though returning true!

After sifting through tons of Stack Overflow & other forum posts, I eventually found that TryUpdateModel does not work on fields, only properties. To get it working properly I had to modify my ViewModel to look like so:

public class CompanyViewModel
{
    public Company Company { get; set; }

    public CompanyViewModel(Company company)
    {
        Company = company;
    }

    public CompanyViewModel()
    {
        Company = new Company();
    }
 }

Such a silly mistake, though I feel this point is far overlooked by many of the model binding tutorials I have read.

Hopefully this answer will save someone some time.

阅读全文

相关推荐

最新文章