我是Asp.Net的新手MVC在视图页面中编写了这个java脚本代码,用于创建url动作:
$("#BookName").click(function (event) {
event.preventDefault();
var url = '@Url.Action("Item", "Store", new {parentPartId = "PARENT_ID",UserID="USER_ID"})';
url = url.replace("USER_ID", $("#USERID").val());
url = url.replace("PARENT_ID", $(this).data("id"));
alert(url); //just for debugging
window.location.href = url;
});
并alert(url); //just for debugging
告诉我这个网址:
http://localhost:2345/Store/Item?parentPartId=1&UserID=1
这是我的项目行动:
public ActionResult Item(int parentPartId,int UserID)
{
StoreOnlineEntities1 storeOnline = new StoreOnlineEntities1();
var query_find = (from p in storeOnline.BookDetails
where p.BookID == parentPartId
select new
{
p.BookID,
p.Exaplain
}).ToArray();
ViewBag.Detail = query_find[0].Exaplain;
ViewBag.BookID = query_find[0].BookID;
ViewBag.UserID = UserID;
return View();
}
但运行时,我的应用程序会收到此错误:
The parameters dictionary contains a null entry for parameter 'UserID' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Item(Int32, Int32)' in 'StoreProject.Controllers.StoreController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
我怎样才能解决问题?谢谢。
答案 0 :(得分:1)
试试这个
window.location.href = encodeURI(url);
答案 1 :(得分:0)
检查以下代码以获取创建网址:
$("#BookName").click(function (event) {
event.preventDefault();
var pathname = window.location.pathname;
var loc = window.location;
var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
// to show it in an alert window
var fullUrl = loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length)) + "Item";
window.location = fullUrl + "?parentPartId =" + $(this).data("id")+"&UserID="+$("#USERID").val();
//you can use window.location.href as well
});
行动应该是:
[HttpGet]
public ActionResult Item(int? parentPartId,int? UserID)
{