0

I have an MVC controller that accepts two string parameters but I will only ever use one or the other. I'm not sure how to best handle the situation. I need to find a way to pass a NULL for which ever parameter will not be used. The way I have it set up now passes the parameters get to the Action but the unused parameter is empty, I need it to be NULL and everything will work as I need. I know I could do an "if" statement and build the @URL.Action link dynamically but that seems clunky. I also saw some posts that suggest a custom route but I would like to hear from users here before I go that route. There must be an easier way.

My function to route to the new 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
})

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();

}

4

1 回答 1

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;
});
于 2013-07-18T21:20:29.943 回答