开发者

Model validation with viewModel don't works

I use viewModels to communicate between my controller and my view. To get model validation, i use a partial class like this :

[MetadataType(typeof(EvaluationValidation))]
public partial class Evaluation
{
    public class EvaluationValidation
    {
        [DisplayName("Title of evaluation")]
        [Required( ErrorMessage="Please give a title")]
        public string Title { get; set; }
    }
}

The Displayname is binded to view with no problem but when i try to submit the view, i get this error :

The model item passed into the dictionary 开发者_如何学JAVAis of type 'FOOBAR.Models.Evaluation', but this dictionary requires a model item of type 'FOOBAR.Areas.Evaluation.ViewModels.EvaluationFormViewModel'.

This is the code used in my controller

    [HttpPost]
    public ActionResult Create(FormCollection formValues)
    {
        Models.Evaluation data = new Models.Evaluation();
        if (TryUpdateModel(data, "evaluations"))
        {
            this.daoe.Create(data);
            return RedirectToAction("Index");
        }
        return View(data);
    }

And this is my viewModel

public class EvaluationFormViewModel
{
    public FOOBAR.Models.Evaluation evaluations;
    public SelectList selectlist_evaluationtypes { get; set; }
    public SelectList selectlist_evaluationstatus { get; set; }
}

Have you got an idea ? Thank's by advance


You are passing a Models.Evaluation instance to your view, which is bound to a model of another type.

Models.Evaluation data = new Models.Evaluation();
if (TryUpdateModel(data, "evaluations"))
{
   // ...
}
return View(data);

If TryUpdateModel returns false (which happens when the form does not pass validation, for example), you are effectively passing data to the View, which is of type Models.Evaluation.

Try mapping it to type FOOBAR.Areas.Evaluation.ViewModels.EvaluationFormViewModel before passing it to the view.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜