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

}

1
  • If you pass the parameter it can't distinguish between NULL and EMPTY (so it'll be just empty). Even if there may be a trick for that...an IF will make your code much more clear (even for you when you'll read it again after 1 year). Commented Jul 18, 2013 at 21:02

1 Answer 1

1

One possible solution would be to check inside the controller action if a parameter is empty, set it to null before using it.

Another possibility is to compose one or the other url on the client:

$('#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;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.