I have a view page with multiple models and i am having trouble getting the data to display but i could save any added data just fine. It is just displaying the data on page load tells me that the model i am passing in passes a null reference.
Main view:
@model Project.Models.ProfileModel
@{
ViewBag.Title = "Profile";
}
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
</hgroup>
<div id="wrap">
<div id ="right">
@(ViewBag.HasLocalPassword ? Html.Partial("_ChangePasswordPartial", Model.PasswordModel) : Html.Partial("_SetPasswordPartial", Model.PasswordModel))
</div>
<div id="left">
@Html.Partial("_UsernamePartial", Model.UsernameModel)
@Html.Partial("_PlayNamePartial", Model.PlayNameModel)
</div>
</div>
My models:
public class ProfileModel
{
public PasswordModel PasswordModel { get; set; }
public PlayNameModel PlayNameModel { get; set; }
public UsernameModel UsernameModel { get; set; }
}
Controller - For each model i have a get and post method except the PlayName
just has a GET.
UserName Controller:
public ActionResult _UsernamePartial()
{
var usernameModel = new UsernameModel();
using (var db = new DataContext())
{
usernameModel.Username =
(from u in db.Users where u.ID == WebSecurity.CurrentUserId select u.Username).FirstOrDefault();
}
return PartialView(usernameModel);
}
@Html.Partial("_UsernamePartial", Model.UsernameModel)
shows Object reference not set to an instance of an object.
and i am not sure how to properly fix this.
public ActionResult Profile(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: "";
ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.ReturnUrl = Url.Action("Profile");
return View();
}
Post for Username:
[HttpPost]
public ActionResult _UsernamePartial(UsernameModel usernameModel)
{
if (ModelState.IsValid)
{
using (var db = new DataContext())
{
User user = db.Users.FirstOrDefault(u => u.ID == WebSecurity.CurrentUserId);
user.Username = usernameModel.Username;
db.SaveChanges();
}
}
return View("_UsernamePartial");
}
Username Page:
@model Acatar.Models.UsernameModel
@using (Html.BeginForm("_UsernamePartial", "Account")) {
<p id="legend">Username</p>
@Html.TextBoxFor(m=>m.Username)
<button type="submit" value=" Username">Save</button>
}
Your Null Ref was the result of View() Factory call without the bound model.