如果Null在模型中 - ASP.NET MVC4

时间:2014-04-09 11:44:18

标签: asp.net-mvc-4 if-statement

我可以声明" IF"声明或类似于MVC中的模型,例如这是我的代码:

namespace SolrWeb.Models
{
    public class SolrVariables
    {
    [SolrField("sequentialid")]
    public long Sequ { get; set; }

    [SolrField("exchangestatus")]
    public int ExtId { get; set; }

    [SolrField("msgtype")]
    public ICollection<string> MsgT { get; set; }
    ...

如此变量:

    [SolrField("msgtype")]
    public ICollection<string> MsgT { get; set; }
    -> this if is NULL return Default "0" else return "String" 

我忘记了下一个重要的代码:

...
@foreach (var row in Model)
{
<tr>
    <td>@row.Sequ</td>
    <td>@row.ExtId</td>
    <td>@row.MsgT.First()</td>
    Because of ".First" if is Null code brake, this is why I whant to have If
    in my Model, so if it is Null, it won't brake...

感谢大家的帮助

1 个答案:

答案 0 :(得分:0)

你可以这样做:

private ICollection<string> _msgT;

[SolrField("msgtype")]
public ICollection<string> MsgT 
{ 
    get 
    {
        if(_msgT == null)
        {
            return new ICollection<string>() With {"0"};
        }

        return new ICollection<string>() With {"String"};
    };

    set(ICollection<string> value)
    {
        _msgT = value
    };
 }