asp.net mvc 2 - 模型绑定和选择列表
我有以下选择列表:
<select d="Owner_Id" name="Owner.Id">
<option value="">[Select Owner]</option>
<option value="1">Owner 1</option>
<option value="2">Owner 2</option>
<option value="3">Owner 3</option>
</select>
它绑定到:
public class Part
{
// ...other part properties...
public Owner Owner {get; set;}
}
public class Owner
{
public int Id {get; set;}
public string Name {get; set;}
}
我遇到的问题是,如果选择了 [Select Owner]
选项,则会抛出错误,因为我绑定了一个空字符串到一个整数。我想要的行为是空字符串只会导致零件上的所有者属性为空。
有没有办法修改零件模型绑定器以获得此行为?因此,在绑定 Part 的 Owner 属性时,如果 Owner.Id 为空字符串,则仅返回 null Owner。我无法修改所有者模型绑定器,因为我需要其自己的控制器中的默认行为(添加/删除所有者)。
I have the following select list:
<select d="Owner_Id" name="Owner.Id">
<option value="">[Select Owner]</option>
<option value="1">Owner 1</option>
<option value="2">Owner 2</option>
<option value="3">Owner 3</option>
</select>
It gets bound to:
public class Part
{
// ...other part properties...
public Owner Owner {get; set;}
}
public class Owner
{
public int Id {get; set;}
public string Name {get; set;}
}
The problem I'm running into is that if the [Select Owner]
option is selected then an error is thrown because I'm binding an empty string to an int. The behavior I want is an empty string just results in a null Owner property on Part.
Is there a way to modify the Part model binder to get this behavior? So when binding the Owner property of Part, if Owner.Id is an empty string then just return a null Owner. I can't modify the Owner model binder as I require the default behavior in its own controller (adding/removing Owners).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试自定义模型绑定器:
然后:
或全局注册它:
You could try a custom model binder:
And then:
or register it globally: