2017-07-03 73 views
0

使用AJAX我有一个请求之下 http://localhost:16770/Admin/Category/GetColorByCode/#00aabb如何通过“#”字符作为MVC

由于该请求包含#和控制方法,从URL参数没有被称为在asp.net核心MVC。

这里是Ajax代码

var ajaxUrl = ApplicationRootUrl("GetColorByCode", "Category") + "/" + self.colorCode(); 
$.ajax({ 
     type: "GET", 
     contentType: "application/json; charset=utf-8", 
     url: ajaxUrl, 
     dataType: "json", 
     success: function (data) { 
      if (data.isSuccess) { 

      } else { 
       self.Error(true); 
       self.message(data.successMessage); 
      } 

      $('#LoadingImage').hide(); 
     }, 
     error: function (err) { 

     } 

}); 

服务器端代码

[HttpGet("colorCode")] 
public JsonResult GetColorByCode(string colorCode) 
{ 
} 

控制器方法不被调用作为查询字符串包含#。我知道这是因为#。我想通过#。我怎么能,我在asp.net核心使用ajax调用了这个。

+1

[百分比编码。](https://en.wikipedia.org/wiki/Percent-encoding)更换与%23的散列。 – Curiousdev

+0

这是唯一的解决方案?我怎样才能直接发送 –

+1

你可以在ajax'var daata = {'colorCode':'#abc'}'中传递一个数据参数,然后stringify到json'JSON.stringify(daata)'并且作为一个数据参数传递在ajax'data:JSON.stringify(daata)'中,'或者你可以把你的ajax请求作为'POST',以及如果你想找到'get'和'post'之间的区别,请查找[本文] ://www.sitepoint.com/key-differences-post/) – Curiousdev

回答

0

我已添加NetFiddle。它的工作原理here

您可以使用Url.Action()用JavaScript encodeURIComponent()功能然后解码"#value"Server.UrlDecode()功能的遥控器侧像以下。

// jquery的

var ajaxUrl = '@Url.Action("GetColorByCode", "Home")' + '?value=' + encodeURIComponent('#value'); 
$.ajax({ 
     type: "GET", 
     contentType: "application/json; charset=utf-8", 
     url: ajaxUrl, 
     dataType: "json", 
     success: function (result) { 
     console.log(result); 
     if (result.isSuccess) { 
      alert(result.data) 
     } else { 
      self.Error(true); 
      self.message(data.successMessage); 
     } 

        $('#LoadingImage').hide(); 
     }, 
     error: function (err) { 

     }     
}); 

//控制器

[HttpGet] 
public JsonResult GetColorByCode(string value) 
{  
    var resultValue = Server.UrlDecode(value); 
    return Json(new { data = resultValue, isSuccess = true}, JsonRequestBehavior.AllowGet);       
}