[英]Razor view model binding use javascript function
I have following model binding in reazor view .cshtml我在 reazor 视图 .cshtml 中有以下模型绑定
@Html.TextBoxFor(m => m.cDate,
new{
@id = "textd",
@type = "text"
}
)
I want to call a javascript function before binding like below我想在绑定之前调用一个 javascript 函数,如下所示
@Html.TextBoxFor(m => updatedateFormat(m.cDate),
new{
@id = "textd",
@type = "text"
}
)
updatedateFormat is a javascript function. updatedateFormat是一个 javascript 函数。
I do have many options to do with c# only, But I am curious to know can we use javascript function with model binding.我确实有很多选择只与 c# 相关,但我很想知道我们是否可以将 javascript 函数与模型绑定一起使用。
I tried like below我试过如下
@{
string ccDate= @Convert.ToString("updatedateFormat(@Model.cDate)");
}
@Html.TextBoxFor(m => ccDate,
new
But not working但不工作
Please advise.请指教。 Thanks谢谢
Since it is not possible to trigger a Javascript
function, when an input element or any other html
element is rendered, you can use the document.ready
event to achieve what your want:由于无法触发Javascript
函数,因此在呈现 input 元素或任何其他html
元素时,您可以使用document.ready
事件来实现您想要的:
@Html.TextBoxFor(m =>m.cDate,
new{
@id = "textd",
@type = "text",
}
)
And when the document is ready:当文件准备好时:
$(document).ready(function () {
var ccDate= document.getElementById('textd');
updatedateFormat(ccDate);
})
Or you could add a custom attribute such as data-onload
to simulate a on load event:或者您可以添加自定义属性,例如data-onload
来模拟加载事件:
@Html.TextBoxFor(m => m.cDate,
new{
@id = "textd",
@type = "text",
data_onload="updatedateFormat('@Model.cDate')"
}
)
And when the document is ready:当文件准备好时:
$(document).ready(function () {
$('[data-onload]').each(function(){
eval($(this).data('onload'));
});
})
If you only want to format the value of your property, you can do that using ToString()
function inside the HTML helper:如果您只想格式化您的属性值,您可以使用 HTML 助手中的ToString()
函数来完成:
@Html.TextBoxFor(m =>m.cDate,
new{
@id = "textd",
@type = "text",
@Value = Model.cDate.ToString("yyyy/MM/dd")
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.