添加了 SqlFunctions.StringConvert 不必要的填充
在我的 ViewModel 中,我返回以下下拉列表:
public IEnumerable<SelectListItem> Statuses
{
get
{
using (var context = new AssetManager.Models.AssetManagerEntities())
{
var query = from status in context.AssetStatuses
where status.Reserved != true
select new SelectListItem()
{
Value = SqlFunctions.StringConvert((double)status.Id),
Text = status.Name,
Selected = false
};
return query.ToList();
}
}
}
然后在我的视图中,它有点像这样:
@Html.DropDownListFor(model => model.Status, (IEnumerable<SelectListItem>)Model.Statuses)
这一切都正常,除了 SqlFunctions.StringConvert 默认情况下使字符串长度为 10,所以我最终得到html 中的 this:
<option value=" 7">Free to loan</option>
记下值字段中的间距。这是一个问题,因为我的 ViewModel 要求该字段为 int。
我可以简单地指定长度参数,但这不是动态的。
有没有人见过这个问题,或者有解决方案?
谢谢, 缺口
In my ViewModel i am returning the following for a dropdown list:
public IEnumerable<SelectListItem> Statuses
{
get
{
using (var context = new AssetManager.Models.AssetManagerEntities())
{
var query = from status in context.AssetStatuses
where status.Reserved != true
select new SelectListItem()
{
Value = SqlFunctions.StringConvert((double)status.Id),
Text = status.Name,
Selected = false
};
return query.ToList();
}
}
}
Then in my View it goes a little like this:
@Html.DropDownListFor(model => model.Status, (IEnumerable<SelectListItem>)Model.Statuses)
This all works ok, except that SqlFunctions.StringConvert, by default makes the string a length of 10, so i end up with this in the html:
<option value=" 7">Free to loan</option>
Take note of the spacing in the value field. This is a problem, because my ViewModel requires this field to be an int.
I could simply specify the length parameter but this is not dynamic.
Has anyone seen this problem, or have a resolution to it?
Thanks,
Nick
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将其更改为:
Change it to:
下面更新
蒂姆的答案是比这个更好的解决方案,但我无法删除已接受的答案,并且OP已没有回应我接受他的答案的请求。
原始答案
最简单的方法可能是将转换工作卸载到服务器上,而不是数据上下文上。如果您将数据层与表示层分离,这会自动发生。但为了简单起见,我将坚持使用当前的架构:
Update
Tim's answer below is a better solution than this one, but I am unable to delete the accepted answer, and the OP has not responded to my requests to accept his answer.
Original Answer
The easiest way to do this would probably be to offload the conversion effort onto your server, rather than the data context. If you were separating your data tier from your presentation tier, this would happen automatically. But for simplicity's sake, I'll just stick with your current architecture:
与 LINQ to Entities 配合使用的另一种选择是通过隐式类型转换进行串联,例如
Value = "" &状态.Id
。但是,如果您想使用此方法进行多重串联,这将导致必须解决的问题。One other option that works with LINQ to Entities is to do a concatenation with an implicit type conversion such as
Value = "" & status.Id
. However, this will cause issues that have to be worked around if you want to use multiple concatenation using this method.