因此,我们可以从控制器返回部分视图,如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public PartialViewResult Address()
{
Address a = new Address { Line1 = "111 First Ave N.", Line2 = "APT 222", City = "Miami", State = "FL", Zip = "33133" };
return PartialView(@"~/Views/Home/_Address.cshtml", a);
}
}
}
但是,我应该如何使用返回的局部视图?我在Views / Home下创建了_Address.cshtml,如下所示:
@model MvcApplication1.Models.Address
<p>
This is a partial view of address.
</p>
<p>
@Model.City
</p>
而且,在Views / Home / Contact.cshtml的末尾,我添加了这一行:
@Html.Partial(@"~/Views/Home/_Address.cshtml")
我希望看到我所在的城市,但它并没有显示出来。我很困惑。
答案 0 :(得分:7)
当partial采用与您所包含的方法不同的模型时,需要使用带有模型参数的重载并为视图提供模型。默认情况下,它使用与包含视图相同的模型。通常,只有在不同的非共享文件夹中才需要路径。如果它位于同一个控制器的文件夹中,那么仅使用该名称即可。
@Html.Partial("_Address", Model.Address)
另一方面,如果您要问我如何从我的网页中包含的操作中获取部分视图,那么您希望使用Action
方法而不是Partial
方法方法
@Html.Action("Address")
修改强>
要进行部分工作,您需要将Contact
模型传递给联系人视图。
public ActionResult Contact()
{
var contact = new Contact
{
Address = new Address
{
Line1 = "111 First Ave N.",
Line2 = "APT 222",
City = "Miami",
State = "FL",
Zip = "33133"
}
}
return View(contact);
}
答案 1 :(得分:4)
为您演示:
public ActionResult Update(Demo model)
{
var item = db.Items.Where(item => item.Number == model.Number).First();
if (item.Type=="EXPENSIVE")
{
return PartialView("name Partial", someViewModel);
}
}