C# 如何通过列表中元素的交互来获取Id<;元素>;在.NET框架中
我有一个元素列表,这些元素通过for循环显示在页面上。我想将所选元素的数据获取到asp.net视图中。我怎么能意识到这一点 这是控制器返回元素列表的操作:C# 如何通过列表中元素的交互来获取Id<;元素>;在.NET框架中,c#,.net,asp.net-mvc,model-view-controller,arraylist,C#,.net,Asp.net Mvc,Model View Controller,Arraylist,我有一个元素列表,这些元素通过for循环显示在页面上。我想将所选元素的数据获取到asp.net视图中。我怎么能意识到这一点 这是控制器返回元素列表的操作: public ActionResult MainContent() { SiteContext db = new SiteContext(); db.SaveChanges(); var model = db.Posts.ToList(); return PartialView("MainContent",
public ActionResult MainContent()
{
SiteContext db = new SiteContext();
db.SaveChanges();
var model = db.Posts.ToList();
return PartialView("MainContent", model);
}
主要内容的局部视图:
@model IEnumerable<LayersDAL.Entity.Post>
@for (int i = 0; i < Model.Count(); i++)
{
<ul>
<li>
//Here is I'm trying to send element Id of current loop iteration to CurrentPost but something goes wrong :(
<a class="post-ref" href="@Url.Action("CurrentPost", "Notes", new { Model.ToList()[i].PostId })">
<h2>@Html.DisplayFor(modelItem => Model.ToList()[i].Title)</h2>
<p>
</p>
</a>
</li>
</ul>
}
CurrentPost的局部视图:
<div class="modal-post">
<div class="modal-post-divs">
<span class="close">×</span>
</div>
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div>
<label>@Model.Title</label>
</div>
</div>
&时代;
@Html.ValidationSummary(true,“,new{@class=“text danger”})
@模型名称
那么,我能做什么呢?:)
UPD:
谢谢大家,我解决了这个问题:)FirstOrDefault()如果找不到项,则返回null,因此您的模型将为null
public ActionResult CurrentPost(int? id)
{
SiteContext db = new SiteContext();
var post = db.Posts.FirstOrDefault(p => p.PostId == id);
return PartialView(post);
}
您可以在视图中检查它以避免错误
@if(Model != null)
{
// your code.
}
else
{
<p>No item found </p>
}
@if(Model!=null)
{
//你的密码。
}
其他的
{
没有找到任何项目
}
FirstOrDefault()如果找不到项,则返回null,因此您的模型将为null
public ActionResult CurrentPost(int? id)
{
SiteContext db = new SiteContext();
var post = db.Posts.FirstOrDefault(p => p.PostId == id);
return PartialView(post);
}
您可以在视图中检查它以避免错误
@if(Model != null)
{
// your code.
}
else
{
<p>No item found </p>
}
@if(Model!=null)
{
//你的密码。
}
其他的
{
没有找到任何项目
}
将链接代码更改为以下内容:
<a class="post-ref" href="@Url.Action("CurrentPost", "Notes", new { id = Model[i].PostId })">
<h2>@Html.DisplayFor(modelItem => Model[i].Title)</h2>
<p>
</p>
</a>
将链接代码更改为以下内容:
<a class="post-ref" href="@Url.Action("CurrentPost", "Notes", new { id = Model[i].PostId })">
<h2>@Html.DisplayFor(modelItem => Model[i].Title)</h2>
<p>
</p>
</a>
首先检查,您的模式是否包含数据。首先检查,您的模式是否包含数据。做得好:)感谢我们可以创建一个检查模型是否为空的通用方法吗?做得好:)感谢我们可以创建一个检查模型是否为空的通用方法吗?