I am new to MVC getting exception when i try to render the textbox dynamically with the following code. Please help
"Object reference not set to an instance of an object" Exception occurs with the following code
VIEW Code
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Hello_World_MVC.Models.ModelProperty>" %>
<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">.
<%using (Html.BeginForm())
{ %>
<%foreach (var cbName in Model.Obj)//Exception throws here NullreferenceException
{%>
<input id="cbID" type="checkbox" name="SelectedObject" value="<%=cbName.OptionID%>"/>
<%} %>
<%} %>
</asp:Content>
Control page
public ActionResult About()
{
AboutModels ObjAM = new AboutModels();//model class name
ModelProperty ObjMP = new ModelProperty();
ObjMP.Obj = ObjAM.dbValue();
return View();
}
Model Page #region ModelsDTO
public class ModelProperty
{
private List开发者_如何转开发<double> cbvalues = new List<double>();
public List<double> cbValues { get; set; }
private List<Option> obj = new List<Option>();
public List<Option> Obj { get; set; }
}
#endregion
public class AboutModels
{
DataClasses1DataContext dbObj = new DataClasses1DataContext();
public List<PollOption> dbValue()
{
List<Option> opValue = new List<Option>();
opValue = (from Value in dbObj.Options
select Value).ToList<Option>();
return opValue;
}
}
Please help..Thanks in advance
Change return View();
in AboutAction
with return View(ObjMP);
. Your mistake is that you forget to pass generated model to view, and it is null.
you should enter the model/object as paramter for returning the view so in your case it is
return View(ObjMP);
hth
You need to pass the model to the view. Try this..
public ActionResult About()
{
AboutModels ObjAM = new AboutModels();//model class name
ModelProperty ObjMP = new ModelProperty();
ObjMP.Obj = ObjAM.dbValue();
return View(ObjAM);
}
精彩评论