【问题标题】:ASP.NET MVC Create method null int [duplicate]ASP.NET MVC 创建方法 null int [重复]
【发布时间】:2014-04-02 15:59:15
【问题描述】:

您好,我的 create 方法收到一个 int,我怎样才能让它可以为空?所以我有时可以在没有 int 的情况下使用这种方法。

   public ActionResult Create(int id)
    {
        var model = new Job { IncidentID = id };
        ViewBag.ActionCode = new SelectList(db.ActionTypes, "ActionCode", "ActionCode");

        return View(model);
    }

显然我已经尝试过

(int ? id)

但是在这里它不高兴,因为它不能转换 int?到这里:

var model = new Job { IncidentID = id };

【问题讨论】:

  • 这会给你一个编译器错误,如果你在网上搜索它会给你答案:使用id.Value
  • id不通过时应该分配给IncidentID什么?
  • 您还必须更改 class Job int? 上的 IncidentID 属性。
  • 我不是 100% 了解您的要求,但 IncidentID 必须支持空值,或者您必须先将 id 转换为非空值,然后才能进行该分配。跨度>
  • @Sergey Berezovskiy 没有任何事件ID 将由用户输入定义。 @Mike Cheel 目前可以为空,但在写入数据库时​​不能为空。

标签: c# asp.net-mvc asp.net-mvc-5


【解决方案1】:

试试这个

public ActionResult Create(int? id)
{
    var model = new Job { IncidentID = id.GetValueOrDefault(0) };
    //or var model = new Job { IncidentID = (int.parse(id) };
    ViewBag.ActionCode = new SelectList(db.ActionTypes, "ActionCode", "ActionCode");

    return View(model);
}

GetValueOrDefault(0) 有助于在 id 没有值或 null 时分配零

或 试试这个

 var model = new Job { IncidentID = id.HasValue ? id.Value : 0 };

【讨论】:

  • 你怎么知道应该分配0以防id没有通过?
  • 我要补充的是 GetValueOrDefault 有一个重载,可以指定默认值。 msdn.microsoft.com/en-us/library/3d6d4f1d(v=vs.110).aspx
  • 我已经更新了我的回答者的
  • 我会删除反对票,但这仍然是一个猜测。如果没有通过 id,也许 OP 不需要创建新的 Job
  • 我了解您想帮助 OP,但 OP 没有提供足够的信息来回答他的问题。您的回答证明了one of the ways to assign a nullable int to an int,但这对 OP 没有帮助。 @Sergey 的问题必须由 OP 回答才能正确回答这个问题,而不仅仅是任务。另外,请考虑以重复投票结束,而不是给出已经存在多次的答案。
【解决方案2】:

只需检查id 是否有值并仅在它有时分配IncidentID

public ActionResult Create(int? id)
{
    var job = new Job();
    if (id.HasValue)
        job.IncidentID = id.Value;

    ViewBag.ActionCode = new SelectList(db.ActionTypes, "ActionCode", "ActionCode");
    return View(job);
}

【讨论】:

  • 我已经这样做了,先生,请看我的回答
  • @RameshRajendran 不,你没有。您正在分配0
  • 是的id.HasValue 是假的,然后我分配了0。
  • @RameshRajendran 我应该向你解释一下不同之处吗?
  • 好的,先生。我明白了。谢谢
【解决方案3】:

您可以使用nullable int 作为您的方法参数。 Nullable<T> 有一个 HasValue 方法,用于检查是否已将值分配给可空变量。如果返回true,则使用Value属性获取变量的值。

public ActionResult Create(int? id)
{
  var model=new Job();
  if(id.HasValue)
  {
    model.IncidentID=id.Value;
  }
  //to do :return something
}

【讨论】:

  • 我已经这样做了,先生,请看我的回答
猜你喜欢
  • 1970-01-01
  • 2010-12-19
  • 1970-01-01
  • 1970-01-01
  • 2013-01-09
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
相关资源
最近更新 更多