使用超链接上的GUID编辑详细信息(非可空类型System.Int32错误)

时间:2016-10-18 17:28:52

标签: c# asp.net-mvc

当我点击下面的超链接时,我收到“非可空类型System.Int32错误”。

@Html.ActionLink("Edit", "Edit", "Student", new { id = item.Id },null)

班级结构

public class BasicInfo
{
 public Guid Id { get; set; }
 public string FirstName { get; set; }
 public string LastName { get; set; } 
 .......
}

控制器的查看方法

public ActionResult Edit(int id)
{
  if (id != null)
  {
   //dbConnect's edit method return the records base on selected records
   //edit method calling store procedure to fetch records and return list
   return View("Edit", dbConnect.edit(ObjInfo));
  }
 return View();
}

如果您看到下面的截图,那么您注意到GUID正在传入URL,但数据库中不存在“00000000-0000-0000-0000-000000000000”。

根据我的理解,URL必须包含GUID,它将数据库存储在相应的记录中。

got error after clicked on edit hyperlink Table Structure

如果需要更多详细信息,请与我们联系

1 个答案:

答案 0 :(得分:0)

您似乎需要根据here添加自定义模型绑定器:

  

当你需要在你的行动中有一个Guid类型的参数时,是   需要创建自定义模型绑定器。这是我的习惯   ModelBinder的:

public class GuidModelBinder : IModelBinder 
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var parameter = bindingContext
            .ValueProvider
            .GetValue(bindingContext.ModelName);

        return Guid.Parse(parameter.AttemptedValue);
    }
}
  

现在,我们需要在启动应用程序时注册我们的自定义modelBinder。我们可以这样做(Application_Start方法Global.asax.cs):

ModelBinders.Binders.Add(typeof(Guid), new GuidModelBinder());
  

因此我们的行动如下:

public ActionResult Edit(Guid id)
{
    // Your code here
}
  

就绪!现在一切都像预期的那样。