将 C# 模型从视图传递给 Javascript [英] Pass C# Model from View to Javascript
问题描述
我正在将此 ViewModel 传递给我的视图:
I'm passing this ViewModel to my View:
public class DashboardViewModel
{
public List<UserTask> UserTasks {get; set;}
public List<WorkItem> WorkItems {get; set;}
}
从视图中我像这样遍历工作项:
and from within the View I'm iterating through the WorkItems like this:
@foreach (var item in Model.WorkItems)
{
@item.Name
@item.HoursLogged
<button value="@item">UPDATE</button>
}
当我点击按钮时,jQuery 函数会打开一个模态.
When I click on the button a jQuery function is opening up a modal.
我需要将项目传递给模式以显示所有项目信息.
I need to pass to the modal the item in order to display all the item infos.
这是javascript函数:
This is the javascript function:
$(buttonEl).click(function () {
//code to open modal
var item = this.value;
});
this.value"传入的值不是一个对象,而是一个带有WorkItem命名空间的字符串.
The value passed in "this.value" is not an object but a string with the namespace of the WorkItem.
我也尝试过使用内联 onclick 函数:
I have also tried with inline onclick function:
<button onclick="openModal('@item')">UPDATE</button>
但结果相同.
有什么想法吗?
推荐答案
我通常使用它来从 MVC 转换为 javascript!
I normally use this to translate from MVC to javascript!
@Html.Raw(Json.Encode(item))
这篇关于将 C# 模型从视图传递给 Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!