2017-04-26 55 views
0

我的类和视图模型,通过JavaScript访问嵌套模型在asp.net MVC

public class MyClass { 
[Key] public int Id {get;set;} 
public name {get;set;} ....etc. 
} 

public class MajorViewModel { 
[key] public string id{get;set;} 
public List<MyClass> myClass {get;set;} 
...etc; 
} 

在控制器

public ActionResult viewDetail() { 
MajorVeiwModel mv = new MajorViewModel() 
... 
.. 
    return View(mv); 
} 

儿童局部视图

@model namespace.MyClass 
<div> @html.DisplayNameFor(model=>model.id) 
<div> @html.DisplayFor(model=>model.id) 
    ....and tens of other properties.. 

看来,我有

@model namespace.MajorViewModel 
<div> @html.DisplayNameFor(model=>model.id) 
     @html.DisplayFor(model=>model.id) </div> 
@for(var I=0; I< Model.myClass.count(); i++) 
{ 
<div>@Html.DisplayFor(model => model.myClass[i].id) 
<a href="#" id="displayId" data-bind: @Model.myClass[i]) <==not sure how to pass data 
} 

<script> 
    $("#displayId").click(function(){ 
     alert(this.name);  <== how to access MyClass[i].name for respective row for which it was clicked. 
    var resultDiv = $('<div id="childView"></div>'); 
    var htmlContext = $(this).parent(); 
    //somehow get the model selected and create html for child 
    var result = ??? <== fill it with child partial view html 
    //TODO ...FILL THE result 
    resultDiv.html(result); 
    alert(resultDiv); 
}); 
</script> 

在上面的代码,我想要绑定的每一行/链接数据,但不知道如何绑定,以便在链接点击,在JavaScript中我能访问所有第i个实例的数据(MyClass [i] .name等数十个属性)由用户点击并显示。 我是否需要序列化数据,但如何链接每行?没有桌子。使用@ Html.HiddenFor。

+1

将属性值添加为'data-'属性 - 例如'

+0

您需要添加每个单独的属性 - 您不能将'model'添加到'data-'属性。另一种方法是只使用相对选择器来获取与'DisplayFor()'方法相关的文本 –

回答

0

而不是“for”语句使用“foreach”语句。

@foreach(var item in Model.myClass) 
{ 
<div>@Html.DisplayFor(m => item.id) 
<a href="#" id="displayId" data-name="item.name" class="clickfunction")>item.Name </a> 
} 

<script> 
    $(".clickfunction").on('click',function(e){ 
    e.preventDefault(); 
    var name = $(this).data("name") 
     alert(name);  
}); 
</script>