![](/img/trans.png)
[英]Call controller method from javascript that return regular view(not partial)
[英]Return a partial view from a controller?
所以,我們可以像這樣從控制器返回一個局部視圖:
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")
我希望看到我的地址所在的城市,但它沒有出現。 我很迷惑。
當部分采用與包含它的方法不同的模型時,您需要使用采用模型參數並為視圖提供模型的重載。 默認情況下,它使用與包含視圖相同的模型。 通常,如果路徑位於不同的非共享文件夾中,則您只需要該路徑。 如果它在同一個控制器的文件夾中,只使用名稱應該可以解決問題。
@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);
}
為您演示:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.