Javascript 파일에서 MVC ViewBag 객체에 액세스 할 수 있습니까?
MVC 애플리케이션의 javascript 파일에서 다음을 수행 할 수 있습니까?
$(function(){
alert(@ViewBag.someValue);
}
현재 오류가 발생합니다.
정의되지 않은 XML 이름 @ViewBag에 대한 참조
나는 현재 이것을 할 방법이 없다고 생각합니다. Razor 엔진은 Javascript 파일을 구문 분석하지 않고 Razor 뷰만 구문 분석합니다. 그러나 Razor보기 내에서 변수를 설정하여 원하는 작업을 수행 할 수 있습니다.
<script>
var someStringValue = '@(ViewBag.someStringValue)';
var someNumericValue = @(ViewBag.someNumericValue);
</script>
<!-- "someStringValue" and "someNumericValue" will be available in script -->
<script src="js/myscript.js"></script>
Joe가 주석에서 지적했듯이 위의 문자열 값은 작은 따옴표가 있으면 중단됩니다. 완전히 철갑 게 만들고 싶다면 모든 작은 따옴표를 이스케이프 처리 된 작은 따옴표로 바꿔야합니다. 문제는 모든 갑작스러운 슬래시가 문제가된다는 것입니다. 예를 들어, 문자열이 " foo \' bar
"이고 작은 따옴표를 바꾸면 " foo \\' bar
" 이 나오고 동일한 문제로 바로 돌아옵니다. (이것은 연쇄 인코딩의 오래된 어려움입니다.) 이것을 처리하는 가장 좋은 방법은 백 슬래시와 따옴표를 특별하게 처리하고 모두 이스케이프 되었는지 확인하는 것입니다 .
@{
var safeStringValue = ViewBag.someStringValue
.Replace("\\", "\\\\")
.Replace("'", "\\'");
}
var someStringValue = '@(safeStringValue)';
JavaScript 파일에는 없습니다.
JavaScript 파일은 클래스를 포함 할 수 있으며 뷰에서 해당 클래스의 새 인스턴스를 인스턴스화 한 다음 ViewBag
클래스 생성자에 값을 전달할 수 있습니다 .
또는 클래스가 아닌 경우 유일한 다른 대안은 data
HTML 요소에서 속성 을 사용 하고 뷰의 속성에 할당 한 다음 JS 파일에서 검색하는 것입니다.
이 입력이 있다고 가정합니다.
<input type="text" id="myInput" data-myValue="@ViewBag.MyValue" />
그런 다음 JS 파일에서 다음을 사용하여 가져올 수 있습니다.
var myVal = $("#myInput").data("myValue");
HTML에서 :
<input type="hidden" id="customInput" data-value = "@ViewBag.CustomValue" />
스크립트에서 :
var customVal = $("#customInput").data("value");
이렇게하려면 자바 스크립트 파일이 서버 측에서 사전 처리되어야합니다. 본질적으로, 그것은해야 될 어떤 종류의 ASP.NET보기 및 script
파일을 참조하는 태그는 기본적으로 해당 뷰에 응답하는 컨트롤러 액션을 참조 할 것.
그것은 당신이 열고 싶지 않은 벌레 캔처럼 들립니다.
JavaScript는 클라이언트 측이므로 값을 일부 클라이언트 측 요소로 설정하고 JavaScript가 해당 요소와 상호 작용하도록하는 것은 어떻습니까? 간접적 인 추가 단계 일 수도 있지만 JavaScript 뷰를 만드는 것보다 훨씬 덜 골치 아픈 것처럼 들립니다.
이 같은:
<script type="text/javascript">
var someValue = @ViewBag.someValue
</script>
그러면 외부 JavaScript 파일 someValue
이 해당 문서의 범위 내에서 JavaScript 변수를 참조 할 수 있습니다 .
또는:
<input type="hidden" id="someValue" value="@ViewBag.someValue" />
그런 다음 숨겨진 입력에 액세스 할 수 있습니다.
실제로 JavaScript 파일을보기로 사용할 수 있도록 만드는 정말 멋진 방법을 생각해 내지 않는 한. 그것은 확실히 해 드리겠습니다, 난 할 수 쉽게 (뷰 엔진을 얻을 것이기 때문에 정말 추한보기 코드 이외의 당신이 가진 것 문제를 생각 매우 그래서 기대 ... 자바 스크립트 무엇에 어떤 면도기가있어 혼동 톤 의 <text>
마크 업) , 따라서 나중에 코드를 지원해야하는 사람에게는 직관적이지 않더라도 매우 멋질 것입니다.
보기를 만들고 부분보기로 반환합니다.
public class AssetsController : Controller
{
protected void SetMIME(string mimeType)
{
this.Response.AddHeader("Content-Type", mimeType);
this.Response.ContentType = mimeType;
}
// this will render a view as a Javascript file
public ActionResult GlobalJS()
{
this.SetMIME("text/javascript");
return PartialView();
}
}
그런 다음 GlobalJS보기에서 다음과 같은 자바 스크립트 코드를 추가합니다 (// 추가하면 Visual Studio intellisense가 자바 스크립트로 읽습니다).
//<script>
$(document).ready(function () {
alert('@ViewBag.PropertyName');
});
//</script>
그런 다음 최종보기에서 이와 같이 자바 스크립트에 대한 참조를 추가 할 수 있습니다.
<script src="@Url.Action("GlobalJS", "Assets")"></script>
Then in your final view controller you can create/pass your ViewBags and it will be rendered in your javascript.
public class MyFinalViewController : Controller
{
public ActionResult Index()
{
ViewBag.PropertyName = "My ViewBag value!";
return View();
}
}
Hope it helps.
I noticed that Visual Studio's built-in error detector kind of gets goofy if you try to do this:
var intvar = @(ViewBag.someNumericValue);
Because @(ViewBag.someNumericValue) has the potential to evaluate to nothing, which would lead to the following erroneous JavaScript being generated:
var intvar = ;
If you're certain that someNemericValue will be set to a valid numeric data type, you can avoid having Visual Studio warnings by doing the following:
var intvar = Number(@(ViewBag.someNumericValue));
This might generate the following sample:
var intvar = Number(25.4);
And it works for negative numbers. In the event that the item isn't in your viewbag, Number() evaluates to 0.
No more Visual Studio warnings! But make sure the value is set and is numeric, otherwise you're opening doors to possible JavaScript injection attacks or run time errors.
Use this code in your .cshtml file.
@{
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var val = jss.Serialize(ViewBag.somevalue);
}
<script>
$(function () {
var val = '@Html.Raw(val)';
var obj = $.parseJSON(val);
console.log(0bj);
});
</script>
In controllers action add:
public ActionResult Index()
{
try
{
int a, b, c;
a = 2; b = 2;
c = a / b;
ViewBag.ShowMessage = false;
}
catch (Exception e)
{
ViewBag.ShowMessage = true;
ViewBag.data = e.Message.ToString();
}
return View(); // return View();
}
in Index.cshtml
Place at the bottom:
<input type="hidden" value="@ViewBag.data" id="hdnFlag" />
@if (ViewBag.ShowMessage)
{
<script type="text/javascript">
var h1 = document.getElementById('hdnFlag');
alert(h1.value);
</script>
<div class="message-box">Some Message here</div>
}
'program story' 카테고리의 다른 글
파이썬에서 재귀 적으로 디렉토리를 복사하고 모두 덮어 쓰는 방법? (0) | 2020.12.08 |
---|---|
위임에 약한 포인터를 사용하는 이유는 무엇입니까? (0) | 2020.12.07 |
기존 인증서 (abc.crt) 및 abc.key 파일에서 키 저장소를 생성하려면 어떻게해야합니까? (0) | 2020.12.07 |
디버깅 할 때 COM 구성 요소 VS2012 호출에서 오류 HRESULT E_FAIL이 반환되었습니다. (0) | 2020.12.07 |
TFS 소스 제어 바인딩 다시 설정 (0) | 2020.12.07 |