Please bear with my noobness, I\'m super new to the MVC pattern.
What I\'m trying to do
I am building a profile information page for re
The best way to handle this situation is to use and pass viewModel to your Profile controller, viewModel is wrapper class for multiple objects that you want to pass to your view.
public class ProfileUserViewModel
{
public ProfileModel ProfileModelObject {get; set;}
public UserModel UserModelObject {get; set;}
}
Your controller should look like:
public ActionResult Profil()
{
var profileModel = db.Users.First(e => e.UserName == WebSecurity.CurrentUserName);
var userModel = //fetch from db.
var pmViewModel = new ProfileUserViewModel
{
ProfileModelObject = profileModel,
UserModelObject = userModel
};
return View(pmViewModel);
}
And finally your view :
@model Applicense.Models.ProfileUserViewModel
<label>Phone number: </label>
@if (Model.ProfileModelObject.PhoneNumber != null)
{
@Model.PhoneNumber
}
else
{
<span class="red">You haven't set up your phone number yet. </span>
}
In your [HttpPost]
profil function, if modelstate.isvalid
is false, you return your edit view, but you need to define your pmViewModel
again , other wise your partial view will not have an object to display. Try using the following and let us know what happens
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult Profil(ProfileModel model)
{
if (ModelState.IsValid)
{
//insert into database
return Content("everything's good");
}
else
{
//outputs form errors
var pmViewModel = new ProfileUserViewModel
{
ProfileModelObject = profileModel,
UserModelObject = userModel
};
return View(model);
}
}
There is an overload of @Html.Partial
which allows you to send ViewData
as defined in your controller - this is the method I generally use for partial views.
In your controller define ViewData["mypartialdata"]
as ViewDataDictionary
. Then in your view
@Html.Partial("_ModifyProfileInfo",ViewData["mypartialdata"])
While I know this question has been asked longtime ago however some people might still face a similar problem. One easy solution I use to pass or have more than one view model on a page is to use a ViewBag to hold the second object and refer to it in the view. See example bellow.
In your controller do this:
Obj2 personalDets = new Obj2();
DbContext ctx = new DbContext();
var details = ctx.GetPersonalInformation;
foreach(var item in details) {
personalDets.Password = item.Password;
personalDets .EmailAddress = item.EmailAddress;
}
ViewBag.PersonalInformation = personalDets;
Then in your view those properties become readily available for you