当我渲染一个局部视图时,我的模型是Null。

16 浏览
0 Comments

当我渲染一个局部视图时,我的模型是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 IList countries;
    }
}

0
0 Comments

当我呈现一个部分视图时,我的模型为空的原因是使用了错误的方法。正确的方法是使用.RenderPartial方法,并将模型对象作为第二个参数传递给它。如果不传递模型对象,则会像模型为空一样呈现视图标记。

要使用.RenderPartial方法,您需要直接在方法中将模型对象作为第二个参数传递给它。例如:.RenderPartial("Search/CountrySearch", yourModelObject)

如果您想通过控制器操作来实现这一点,您需要使用.RenderAction("CountrySearch", "Search")方法,并且CountrySearch方法必须以return PartialView而不是return View结束。

感谢您的反馈。

0
0 Comments

问题的出现原因是在渲染一个部分视图时,模型为空。解决方法是使用Html.RenderAction代替直接渲染视图,并且返回PartialView而不是View。另外,DropDownListFor的第一个参数应该是选中的项。需要修改模型,确保CountryList.json中的数据对模型有效。至于出现的InnerException错误,与这个问题无关,应该另外提出一个相关的问题来解决。

0