【问题标题】:MVC 3 how to pass null parameter using @URL.ActionMVC 3 如何使用@URL.Action 传递空参数
【发布时间】:2013-07-18 00:14:11
【问题描述】:

我有一个 MVC 控制器,它接受两个字符串参数,但我只会使用一个或另一个。我不确定如何最好地处理这种情况。我需要找到一种方法来传递一个不会使用任何参数的 NULL。我设置它的方式现在将参数传递给 Action,但未使用的参数为空,我需要它为 NULL,一切都会按我的需要工作。我知道我可以做一个“if”语句并动态构建@URL.Action 链接,但这似乎很笨拙。我还看到了一些建议自定义路线的帖子,但在我走这条路线之前,我想在这里听取用户的意见。必须有更简单的方法。

我的路由到新 URL 的函数:

$('#poBtn').on('click', function (e) {
  var poId = $('#PoLabel').val();
  var reqId = $('#ReqLabel').val();  
  var url = '@Url.Action("ShipmentsByPo", "Shipping", new {po = "_poId_"  , reqId = "_reqId_" })';
  url = url.replace('_poId_', poId);
  url = url.replace('_reqId_', reqId);
  window.location.href = url;Action
})

行动:

public IEnumerable<ShippingHeaderVM> ShipmentsByPo(string po, string reqID )
{
 object[] parameters = { po, reqID };
 var shipmentsByPo = context.Database.SqlQuery<ShippingHeaderVM>("spSelectLOG_ShippingNoticeByPo {0},{1}",parameters); 
 return shipmentsByPo.ToList();

}

【问题讨论】:

  • 如果你传递参数它不能区分 NULL 和 EMPTY (所以它只是空的)。即使可能有一个技巧......一个 IF 会让你的代码更清晰(即使你会在 1 年后再次阅读它)。

标签: asp.net-mvc


【解决方案1】:

一种可能的解决方案是检查控制器操作内部是否有参数为空,在使用之前将其设置为 null。

另一种可能性是在客户端上编写一个或另一个 url:

$('#poBtn').on('click', function (e) {
    e.preventDefault();

    var poId = $('#PoLabel').val();
    var reqId = $('#ReqLabel').val();  
    var url = '@Url.Action("ShipmentsByPo", "Shipping", new { po = "_poId_" })';
    if (poId != '') { // Might need to adjust the condition based on your requirements
        url = url.replace('_poId_', encodeURIComponent(poId));
    } else {
        url = '@Url.Action("ShipmentsByPo", "Shipping", new { reqId = "_reqId_" })';
        url = url.replace('_reqId_', encodeURIComponent(reqId));
    }

    window.location.href = url;
});

【讨论】:

    猜你喜欢
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2018-04-04
    • 2015-06-18
    • 1970-01-01
    • 2012-05-31
    相关资源
    最近更新 更多