当我渲染一个局部视图时,我的模型是Null。
当我渲染一个局部视图时,我的模型是Null。
我试图在ASP.NET MVC中的另一个视图中呈现一个只包含DropDownList的视图,但出于某种原因,Model为空。我认为这是因为我只调用了视图,而控制器根本没有被调用。我在哪里出错了?也许我的调用方法不正确。
Dropbox视图
@model MyWatch.Models.Countries
@{
ViewBag.Title = "CountrySearch";
Layout = null;
if (Model != null)
{
Html.DropDownListFor(m => m.countries, new SelectList(Model.countries.Select(s => new SelectListItem { Text = s.name, Value = s.code })));
}
else
{
Html.DropDownListFor(m => m.countries, new SelectList(new List
}
}
主视图
@Html.LabelFor(m => m.Country, new { @class = "col-md-2 control-label" }) @{Html.RenderPartial("Search/CountrySearch");}
控制器
public ActionResult CountrySearch() { try { using (StreamReader streamReader = new StreamReader("C:\\Users\\Alex Combe\\Documents\\Visual Studio 2015\\Projects\\MyWatch\\MyWatch\\App_Data\\CountryList.json")) { string json = streamReader.ReadToEnd(); Countries countries = new Countries(); countries.countries = JsonConvert.DeserializeObject>(json); return View(countries); } } catch (FileNotFoundException e) { Console.WriteLine(e.StackTrace); return View(new Countries()); } } }
模型
namespace MyWatch.Models { public class Country { public string name { get; set; } public string code { get; set; } public SelectList selectList { get; set; } } public class Countries { public IListcountries; } }
当我呈现一个部分视图时,我的模型为空的原因是使用了错误的方法。正确的方法是使用.RenderPartial
方法,并将模型对象作为第二个参数传递给它。如果不传递模型对象,则会像模型为空一样呈现视图标记。
要使用.RenderPartial
方法,您需要直接在方法中将模型对象作为第二个参数传递给它。例如:.RenderPartial("Search/CountrySearch", yourModelObject)
如果您想通过控制器操作来实现这一点,您需要使用.RenderAction("CountrySearch", "Search")
方法,并且CountrySearch
方法必须以return PartialView
而不是return View
结束。
感谢您的反馈。