为什么不将 ViewModel 传递给 partialViews。确保 ViewModel 中有不同的属性来保存 PartialView 特定数据和搜索文本。这是一个例子:
模型
public class Product
{
public string Name { get; set; }
public string Type { get; set; }
public string Class { get; set; }
}
视图模型
public class ProductSearch
{
public ProductSearch()
{
q = string.Empty;
Product1 = new Product();
Product2 = new Product();
}
public string q { get; set; }
public Product Product1 { get; set; }
public Product Product2 { get; set; }
}
_Partial1.cshtml
@model Test1.Models.ProductSearch
<div>Product1</div>
@Html.TextBoxFor(a => a.Product1.Name)
_Partial2.cshtml
@model Test1.Models.ProductSearch
<div>Product2</div>
@Html.TextBoxFor(a => a.Product2.Name)
实际视图.cshtml
@model Test1.Models.ProductSearch
@{
ViewBag.Title = "ActualView";
}
<h2>ActualView</h2>
@using (Html.BeginForm())
{
@:SearchText
@Html.TextBoxFor(m => m.q)
Html.RenderAction("_Partial1", Model);
Html.RenderAction("_Partial2", Model);
<input type="submit" runat="server" id="btnSubmit" />
}
临时数据(您将从数据库/任何其他来源获取)
private List<Product> ProductsToSearch()
{
return new List<Product>() { new Product() { Name = "Product One", Class = "A", Type = "High" }, new Product() { Name = "Product Two", Class = "A", Type = "Low" }, new Product() { Name = "Product Three", Class = "B", Type = "High" } };
}
控制器动作
public ActionResult _Partial1(ProductSearch search)
{
Product Product1 = ProductsToSearch().Where(a => a.Class.Equals(search.q) && a.Type.Equals("High")).SingleOrDefault();
search.Product1 = Product1;
return PartialView(search);
}
public ActionResult _Partial2(ProductSearch search)
{
Product Product2 = ProductsToSearch().Where(a => a.Class.Equals(search.q) && a.Type.Equals("Low")).SingleOrDefault();
search.Product2 = Product2;
return PartialView(search);
}
[HttpPost]
public ActionResult ActualView(ProductSearch search)
{
return View(search);
}
public ActionResult ActualView()
{
ProductSearch search = new ProductSearch();
return View(search);
}
现在,如果您输入“A”SearchText
并点击Submit Query
,您将得到两个不同的结果(基本上使用常见的搜索文本,并且基于每个局部视图中的搜索查询,它会生成不同的结果)