我的控制器中有这个代码:
[HttpPost]
public ActionResult Index(double userLat, double userLng)
{
var context = new weddingspreeEntities();
var coordinates = context.Venues
.Select(loc => new { vname = loc.VenueName, lat = loc.VenueLat, lng = loc.VenueLong })
.ToList();
string venueName = string.Empty;
List<SearchModel.DistLocation> venDistList = new List<SearchModel.DistLocation>();
for (int i = 0; i < coordinates.Count; i++)
{
string name = coordinates[i].vname;
double? lat = coordinates[i].lat;
double? lng = coordinates[i].lng;
var loc1Lat = lat.Value;
var loc1Lng = lng.Value;
var loc2Lat = userLat;
var loc2Lng = userLng;
double distance = TrackingHelper.CalculateDistance(
new SearchModel.Location() { Latitude = loc1Lat, Longitude = loc1Lng },
new SearchModel.Location() { Latitude = loc2Lat, Longitude = loc2Lng });
//convert kilometers to miles
double distMiles = distance * 0.621371192;
venueName = name;
venDistList.Add(new SearchModel.DistLocation() { venName = name, Distance = distMiles });
}
return View(venDistList);
}
我的观点中有这个代码:
<div class="row">
<div class="form-group">
<div class="col-md-6">
@using (Html.BeginForm("Search", "Home", FormMethod.Post))
{
@*@Html.TextBoxFor(model => model.cityName)*@
<label>Enter City and State or Zip Code</label>
<input type="text" id="citystate" name="citystate" />
<label>Enter Your Wedding Date</label>
<input class="datefield" data-val="true" data-val-required="Date is required" id="weddingDate" name="weddingDate" type="date" value="1/11/1989" />
<label>Enter Your Guest Count</label>
<input type="text" id="guestcount" name="guestcount" />
<input type="button" id="search" name="search" value="Search for Venues" />
}
</div>
<!--This is the div where the google map will render -->
<div class="col-md-6">
<div id="map_canvas" style="height: 600px;"></div>
</div>
</div>
</div>
<div>
@Html.Partial("_SearchResults")
</div>
为简洁起见,我省略了一些观点
这是我试图渲染的部分视图:
@model IEnumerable<WeddingSpree_Alpha.Models.SearchModel.DistLocation>
@{
Layout = null;
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
foreach (var item in Model)
{
@item.venName
@item.Distance
}
}
我要做的是让用户在搜索框中输入值,然后在点击之后使用foreach语句将结果(在名为venDistList的列表中)发布到视图中。
该模型如下所示:
public class SearchModel
{
public string cityName { get; set; }
public DateTime weddingDate { get; set; }
public int guestCount { get; set; }
public class Location
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
public class DistLocation
{
public string venName { get; set; }
public double Distance { get; set; }
}
}
我希望在页面上的按钮单击(发布)后填充列表结果。我认为我的代码会这样做。我收到以下错误:
System.NullReferenceException:'对象引用未设置为对象的实例'
我知道当您尝试使用尚未填充的模型时会发生错误,但我认为我在控制器代码中执行了此操作?究竟什么可以抛出这个错误?
这是我的局部视图的控制器代码:
public ActionResult _SearchResults(SearchModel model)
{
return View();
}
答案 0 :(得分:1)
如果您至少没有实例化IEnumerable的实例以传回(即使它是空的),那么当您尝试在局部视图中迭代模型时,它将抛出空引用。
编辑:(例如,已修剪代码)您的原始错误是您尝试迭代不存在的对象。下面将向您展示如何让表单上的Ajax调用用户提交以动态生成您的局部视图并将其附加到您的主页
控制器:
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult _SearchResults(string citystate, DateTime? weddingDate, double? guestcount)
{
List<SearchModel.DistLocation> venDistList = new List<SearchModel.DistLocation>();
venDistList.Add(new SearchModel.DistLocation() { venName = "weee1", Distance = 2 });
venDistList.Add(new SearchModel.DistLocation() { venName = "weee2", Distance = 4 });
venDistList.Add(new SearchModel.DistLocation() { venName = "weee3", Distance = 6 });
return PartialView(venDistList);
}
Index.cshtml:
@{
ViewBag.Title = "Home Page";
}
@*This is our form which will feed our user input and drive our search results output*@
<div class="row">
<div class="form-group">
<div class="col-md-6">
<form id="searchMe">
<label>Enter City and State or Zip Code</label>
<input type="text" id="citystate" name="citystate" />
<label>Enter Your Wedding Date</label>
<input class="datefield" data-val="true" data-val-required="Date is required" id="weddingDate" name="weddingDate" type="date" value="1/11/1989" />
<label>Enter Your Guest Count</label>
<input type="text" id="guestcount" name="guestcount" />
<button type="submit" class="btn btn-primary">Search for Venues</button>
</form>
</div>
</div>
</div>
<div class="row">
@*This is where we want our search results to appear when user hits submit on our form*@
<div id="SearchResult"></div>
</div>
@section scripts {
<script>
$(document).ready(function () {
//When the user hit the submit button we will post the form results to our partial view controller
$('#searchMe').submit(function () {
$.ajax({
method: "POST",
url: "/Home/_SearchResults",
data: $(this).serialize(),
success: function (result) {
//When then load our partial view into our containing div on the main page
$('#SearchResult').html(result);
}
});
return false;
});
});
</script>
}
部分视图(_SearchResult.cshtml)
@model IEnumerable<deletemeweb2.Models.SearchModel.DistLocation>
@{
Layout = null;
}
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Search Results</h3>
</div>
<div class="panel-body">
@if (Model != null || Model.Count() < 1)
{
using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
foreach (var item in Model)
{
<p>@item.venName</p>
<p>@item.Distance</p>
}
}
}
else
{
<p>No results found</p>
}
</div>
</div>