MVC问题中的模型绑定器
我收到以下错误 传递到字典中的模型项的类型为“MvcWebApplication.Models.Product”,但此字典需要类型为“MvcWebApplication.ViewModels.ProductCommonViewModel”的模型项。
控制器代码如下:-
public ActionResult Index([Bind(Prefix= "MvcWebApplication.ViewModels.ProductCommonViewModel")] Product product)
View Model class sent to the View:
namespace MvcWebApplication.ViewModels
{
public class ProductCommonViewModel
{
public Product Product { get; set; }
}
}
模型绑定器:
namespace MvcWebApplication.ModelBinders
{
public class ProductBinder : IModelBinder
{
#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase fc = controllerContext.HttpContext.Request;
Product product = new Product();
LaunchSheet launchSheet = null; ;
ProductPricing productPricing = null;
product.LoanTypeId = Convert.ToInt32(fc["rblLoanType"]);
product.ProductTypeId = Convert.ToInt32(fc["ddlproductType"]);
etc...
return Product;
}
}
}
产品类
[ModelBinder(typeof(ProductBinder))]
public partial class Product : IRuleEntity
{
}
我做错了什么?
I am getting the following Error
The model item passed into the dictionary is of type 'MvcWebApplication.Models.Product' but this dictionary requires a model item of type 'MvcWebApplication.ViewModels.ProductCommonViewModel'.
Controller Code is as follows:-
public ActionResult Index([Bind(Prefix= "MvcWebApplication.ViewModels.ProductCommonViewModel")] Product product)
View Model class sent to the View:
namespace MvcWebApplication.ViewModels
{
public class ProductCommonViewModel
{
public Product Product { get; set; }
}
}
Model Binder :
namespace MvcWebApplication.ModelBinders
{
public class ProductBinder : IModelBinder
{
#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase fc = controllerContext.HttpContext.Request;
Product product = new Product();
LaunchSheet launchSheet = null; ;
ProductPricing productPricing = null;
product.LoanTypeId = Convert.ToInt32(fc["rblLoanType"]);
product.ProductTypeId = Convert.ToInt32(fc["ddlproductType"]);
etc...
return Product;
}
}
}
Product Class
[ModelBinder(typeof(ProductBinder))]
public partial class Product : IRuleEntity
{
}
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
并不是绑定被破坏了。 问题是您的强类型视图(aspx/ascx)需要 MvcWebApplication.ViewModels.ProductCommonViewModel 类型的模型,但呈现它的操作正在传递 MvcWebApplication.Models.Product 类型的模型。 请注意,这与您问题中的代码无关; 该错误位于其他地方的“return View(model)”行中。
It's not the binding which is broken. The problem is that your strongly-typed view (aspx/ascx) requires a model of type MvcWebApplication.ViewModels.ProductCommonViewModel, but the action which renders it is passing a model of type MvcWebApplication.Models.Product. Note that this has nothing to do with the code in your question; the bug is in the "return View(model)" line elsewhere.