简体   繁体   English

模型活页夹问题

[英]Model Binder issue

I have a read-only property on a viewmodel that calculates a value from various other properties. 我在viewmodel上有一个只读属性,该属性可从其他各种属性计算值。 I do not want it to be read by the model binder on posts because not all of the source properties are available. 我不希望模型绑定程序在帖子上读取它,因为并非所有源属性都可用。

public class MyView
{
     public int MyReadOnlyProperty
     {
         get 
         {
             int result;
             //do stuff 
             return result;
         }
     }
}

I have added a [Bind(Exclude)] attribute to the controller method like this: 我已经向控制器方法添加了[Bind(Exclude)]属性,如下所示:

[HttpPost]
public ActionResult Create([Bind(Exclude = "MyReadOnlyProperty")]MyView viewModel)
{
}

However, the binder still reads the excluded property. 但是,活页夹仍读取排除的属性。 So when I post back to the above controller method, the MyReadOnlyProperty getter is executed; 因此,当我发回上述控制器方法时,将执行MyReadOnlyProperty getter; but before the controller method is called. 调用控制器方法之前 It seems strange that the binder is reading properties on a post: I would expect it only to be setting them using form values. 活页夹正在读取帖子上的属性似乎很奇怪:我希望它仅使用表单值来设置它们。

Can anyone tell me how to avoid this? 谁能告诉我如何避免这种情况?

Give a try like this : 试试这样:

[HttpPost]
public ActionResult Create(MyView viewModel)
{
   ModelState.Remove("MyReadOnlyProperty");
}

Hope it helps 希望能帮助到你


Edit 编辑

[Bindable(false)]
public int MyReadOnlyProperty
     {
         get 
         {
             int result;
             //do stuff 
             return result;
         }
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM