从控制器返回部分视图

本文关键字:视图 返回部 控制器 | 更新日期: 2023-09-27 17:53:42

所以,我们可以像这样从控制器返回一个局部视图:

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);
        }
    }
}

但是,我应该如何使用返回的部分视图?我创建了_Address。

@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")

我希望看到我的地址的城市,但它没有显示。

从控制器返回部分视图

当局部采用的模型与包含它的方法不同时,您需要使用接受模型参数并为视图提供模型的重载。默认情况下,它使用与包含视图相同的模型。通常,只有当路径位于不同的非共享文件夹中时,才需要该路径。如果它在同一个控制器的文件夹中,只使用名称就可以了。

@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);
}

demo for you:

    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);
    }
}