如何将空字符串作为参数从 Javascript 传递给 MVC ActionMethod

How to pass empty string as a parameter to MVC ActionMethod from Javascript

我有一个 ActionMethod

        [HttpGet]
        [Route("ControllerName/IsUniqueNotificationName/{notificationName}")]
        public IActionResult IsUniqueNotificationName(string notificationName)
        {
            var name = string.IsNullOrEmpty(notificationName);
            var isUnique = 
              this.bannerNotificationService.IsUniqueNotificationName(notificationName);
            return this.Json(isUnique);
        }

我的javascript方法

        checkUniqueNotificationname = function (emailElement) {
        var notificationName = $(emailElement).val();
        let uri = "BannerNotification/IsUniqueNotificationName/" + notificationName;
        $.ajax({
            type: "Get",
            url: common.buildUrlWithBasePath(uri),
            success: function (data) {
                if (data == true) {
                    $("#BannerNotificationName").css({ "border-color": "black" });
                    $("#altFromMessageGroupValue").hide();
                }
                else {
                    $("#BannerNotificationName").css({ "border-color": "red" });
                    $("#altFromMessageGroupValue").show();
                }
            },
            error: function () {
                common.hideLoader();
            }
        });
    };

当我得到 notificationName 值然后它击中了我的 ActionMethod 但是当我得到 notificationName 为空字符串时**(即 notificationName='')** 它没有击中我的端点.相反,它击中了另一个端点,看起来像

        [Route("ControllerName/{banName}")]
        [HttpGet]
        public IActionResult Details(string banName)
        {
        }

谁能帮我解决这个问题

我建议您在服务器中添加另一个方法

[HttpGet]
    [Route("ControllerName/IsUniqueNotificationName")]
    public IActionResult IsUniqueNotificationName()
    {
        var name = "";
        var isUnique = 
          this.bannerNotificationService.IsUniqueNotificationName(name);
        return this.Json(isUnique);
    }

将您的操作更改为:

          [HttpGet]  
        [Route("ControllerName/IsUniqueNotificationName/{notificationName?}")]
        public IActionResult IsUniqueNotificationName(string notificationName)
        {
            var empty = string.IsNullOrEmpty(notificationName);
if (! empty){
}
            var isUnique = 
              this.bannerNotificationService.IsUniqueNotificationName(notificationName);
            return  Json(isUnique);
        }
else return BadRequest();
}

你的 javascript 可能也需要一些改变:

checkUniqueNotificationname = function (emailElement) {
        var notificationName = $(emailElement).val();
       if(notificationName =="")
{
   $("#BannerNotificationName").css({ "border-color": "red" });
     $("#altFromMessageGroupValue").show();
return false;
}
.....your code
  };