我有一个名为" Slider"
的模型using System;
using NHibernate.Mapping.ByCode;
using NHibernate.Mapping.ByCode.Conformist;
namespace BarMotors.Models
{
public class Slider
{
public virtual int Id { get; set; }
public virtual string Photo{ get; set; }
public virtual string LeftText{ get; set; }
public virtual string RightText { get; set; }
public virtual int SortOrder{ get; set; }
public virtual DateTime CreatedAt { get; set; }
public virtual DateTime? UpdatedAt { get; set; }
public virtual DateTime? DeletedAt { get; set; }
public virtual bool IsDeleted
{
get { return DeletedAt != null; }
}
}
public class SliderMap : ClassMapping<Slider>
{
public SliderMap()
{
Table("Sliders");
Id(x => x.Id, x => x.Generator(Generators.Identity));
Property(x => x.Photo, x => x.NotNullable(true));
Property(x => x.LeftText);
Property(x => x.RightText);
Property(x => x.SortOrder, x => x.NotNullable(true));
}
}
}
我也(现在)有这个控制器;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using BarMotors.Models;
using NHibernate.Linq;
namespace BarMotors.Controllers
{
public class SliderController : Controller
{
[ChildActionOnly]
public ActionResult Sliders()
{
List<Slider> model;
new List<Models.Slider>();
model = Database.Session.Query<Slider>().Where(s => s.DeletedAt == null).OrderBy(x=>x.SortOrder).ToList();
return PartialView("_HomeSlider", model);
}
}
}
主要观点
@{
ViewBag.Title = "Homepage";
}
<h1>Homepage</h1>
@Html.Action("Sliders", "Slider")
部分视图
@model BarMotors.Models.Slider
@{
Layout = null;
}
//do something in loop of Slider
在SliderController中我不能将var模型传递给局部视图我要么得到Iqueryable,ienumerable或者错误;
Models.Slider的LIST不能分配给models.Slider类型
非常感谢 西蒙
答案 0 :(得分:1)
如果滑块与父模型无关,则可能需要使用子操作。
你的控制器会有这样的动作:
public class MyController : Controller
{
/* ... your code ... */
[ChildActionOnly]
public ActionResult Sliders()
{
var model = new Models.Slider();
/* ... populate model ... */
return PartialView("your-view-name", model);
}
}
您可以使用HtmlHelper.Action()
方法从父视图中请求子操作:
<div>
<!-- more view markup ... -->
@Html.Action("sliders", "my")
</div>
以这种方式调用Html.Action
方法时,生成的视图(通常是部分视图)将在当前视图中就地呈现。如果您熟悉PHP,它有点类似于include
语句。
答案 1 :(得分:1)
您正在尝试将列表分配给模型,但您已声明了一个非列表类型的模型,因此您要么将其声明为列表类型,要么从结果中选择firstordefault
public class MyController : Controller
{
/* ... your code ... */
[ChildActionOnly]
public ActionResult Sliders()
{
var model = new Models.Slider();
model = Database.Session.Query<Slider>().Where(s => s.DeletedAt == null).OrderBy(x=>x.SortOrder).ToList().FirstOrDefault();
return PartialView("your-view-name", model);
}
}
否则
public class MyController : Controller
{
/* ... your code ... */
[ChildActionOnly]
public ActionResult Sliders()
{
var model = new List<Models.Slider>();
model = Database.Session.Query<Slider>().Where(s => s.DeletedAt == null).OrderBy(x=>x.SortOrder).ToList();
return PartialView("your-view-name", model);
}
}
在部分视图中,您必须将其更改为
@model List<BarMotors.Models.Slider>
@{
Layout = null;
}