错误:值不能为空。参数名称:值

时间:2018-08-14 11:21:48

标签: c# asp.net-mvc entity-framework

我创建了一个搜索页面。有一个专门化的领域,数据通过EF传入。

这是控制器:

public ActionResult Search(string search)
{
    DataTable dt;
    dt = this.GetSPDataTable("getAssociateData");

    List<Associate> list = new List<Associate>();
    list = (from DataRow dr in dt.Rows
            select new Associate
            {
                AssociateId = Convert.ToInt32(dr["AssociateId"]),
                Name = dr["Name"].ToString(),
                Phone = Convert.ToInt64(dr["Phone"]),
                Address = dr["Address"].ToString(),
                SpecializationId = Convert.ToInt32(dr["SpecializationId"]),
                SpcName = dr["SpcName"].ToString()
            }).ToList();
    return View(list.Where(x => x.Name.Contains(search) || search == null).ToList());
    //return View(db.Associates.Where(x => x.Name.Contains(search) || search == null).ToList());

这是视图:

@foreach (var item in Model)
{

    <tr>
        <td>
            @item.Name
        </td>
        <td>
            @item.Phone
        </td>
        <td>
            @item.Address
        </td>
        <td>
            @item.SpcName
        </td>

最后是模型:

[Key]
public int AssociateId { get; set; }

[Required(ErrorMessage = "You must provide a name")]
[MaxLength(10)]
public string Name { get; set; }

[Required(ErrorMessage = "Please Write Your Number ")]
[RegularExpression(@"^([0-9]{10})$", ErrorMessage = "Invalid Mobile Number.")]
public Nullable<long> Phone { get; set; }

[Required(ErrorMessage = "Where do you dwell")]
[MaxLength(50)]
public string Address { get; set; }

[Display(Name = "Specialization")]
[Required(ErrorMessage = "Select any of them")]
public Nullable<int> SpecializationId { get; set; }

[Display(Name = "Specialization")]
public string SpcName { get; set; }

我在输入null时出错。

1 个答案:

答案 0 :(得分:3)

如@CamiloTerevinto所建议:

尝试对其进行过滤之前,请检查search是否为null

使用三元运算符(?:):

return View(search == null ? list
                           : list.Where(x => x.Name.Contains(search)).ToList());

或三行:

if(search == null)
    return View(list);
return View(list.Where(x => x.Name.Contains(search)).ToList();

我之前曾建议以下内容,但以下内容的效率较低:

.Where(x => search == null || x.Name.Contains(search))