【发布时间】:2018-01-10 11:34:37
【问题描述】:
我正在尝试在 ASP.NET MVC 的另一个视图中呈现一个仅由 DropDownList 组成的视图,但由于某种原因,模型为空。我认为这是因为我只调用视图而根本没有调用控制器。我哪里错了?也许我的电话方法不正确。
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<String>()));
}
}
主视图
<div class="form-group">
@Html.LabelFor(m => m.Country, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@{Html.RenderPartial("Search/CountrySearch");}
</div>
</div>
控制器
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<IList<Country>>(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 IList<Country> countries;
}
}
【问题讨论】:
-
因为您没有将模型传递给局部视图,例如
Html.RenderPartial("Search/CountrySearch", Model); -
使用 Action() 方法代替 RenderPartial。 RenderPartial 不会通过控制器,它直接进入视图。
标签: c# asp.net asp.net-mvc asp.net-mvc-4