Tôi personnaly không thích chơi với httpHandlers vì lý do bảo mật. Tôi muốn làm điều tương tự để ngăn chặn việc phải duy trì cùng một cấu trúc thư mục hai lần (trong dạng xem và trong thư mục tập lệnh). Vì vậy, mục tiêu là lưu trữ .js trong cùng thư mục với tệp .cshtml của tôi và không còn lỗi 404 nữa.
Giải pháp
Để đạt được mục tiêu đó, tôi sử dụng một HtmlHelper tùy chỉnh và điều khiển cho javascript gọi.
HtmlHelper
public static MvcHtmlString JScriptBlock<TModel>(
this HtmlHelper<TModel> html
)
{
// Get the physical path of the .js file we are looking for.
string path = ((System.Web.Mvc.RazorView)html.ViewContext.View).ViewPath.Replace(".cshtml", ".js");
path = HostingEnvironment.MapPath(path);
if (!File.Exists(path))
return null;
// We store the physical path in a session variable with GUID as the key
string guid = Guid.NewGuid().ToString();
HttpContext.Current.Session[guid] = path;
// Create the script block where the src points to the JScript controller. We give the GUID as parameter.
return MvcHtmlString.Create("<script src='/JScript/?id=" + guid + "'/>");
}
JScript khiển
public ActionResult Index(string id)
{
// id correspond to the guid generated by the MSRJScript helper
// We look if the physical path of the .js is available in the session variables
if(Session[id] == null)
return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
// If the physical path was found, we simply send the file back to the browser.
string path = Session[id].ToString();
Session.Remove(id);
return File(path, "application/javascript");
}
Sau khi thực hiện, bạn chỉ cần phải thêm đoạn mã sau vào Xem bạn/PartialView
@Html.JScriptBlock()
Nguồn
2015-05-07 12:00:06
này hoạt động, nhưng tôi nghĩ đó là một ý tưởng tốt hơn để không đặt các file js trong thư mục xem. – ErikE
Nó là an toàn hơn không chắc chắn để danh sách trắng các tập tin bạn rõ ràng muốn cho phép theo câu trả lời tại http://stackoverflow.com/questions/604883/where-to-put-view-specific-javascript-files-in-an-asp -net-mvc-ứng dụng thay vì chỉ yêu cầu bộ lọc cho các tệp cshtml. – pwdst
Đối với tôi, tôi đã xây dựng một thiết lập MVC sử dụng nhiều góc cạnh. Tôi cũng đã AMD tất cả mọi thứ với yêu cầu js vì vậy chỉ xem bằng cách sử dụng một số miếng javascript gây ra những tập lệnh java để tải. Như vậy tôi đã phân chia tất cả mọi thứ và nó đã có rất nhiều ý nghĩa để đặt bộ điều khiển góc kết hợp với một thư mục mvc trong thư mục với khung nhìn. Vì vậy, tôi có một cái gì đó như xem \ ControllerName \ ControllerName.cshtml và xem \ Controller \ ControllerName-controller.js. –