How to put a view in another view in asp.net MVC? - asp.net-mvc

Here I have a MainController in which I have two actions named Create and PhotoUpload. Here is the code for Create action.
// GET: Main/Create
public ActionResult Create()
{
return View();
}
// POST: Main/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Email,Password,FirstName,LastName,Gender,Birthday,ProfileImage,AboutUser")] User user)
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
Here is the code for PhotoUpload action.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PhotoUpload(PhotoModel model)
{
if (model.PhotoFile.ContentLength > 0)
{
var fileName = Path.GetFileName(model.PhotoFile.FileName);
var filePath = Server.MapPath("/Content/Users/Images");
string savedFileName = Path.Combine(filePath, fileName);
model.PhotoFile.SaveAs(savedFileName);
}
return View(model);
}
public ActionResult PhotoUpload()
{
return View();
}
And these are the User and Photo models. This is the User Model
public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.Friends = new HashSet<Friend>();
this.Friends1 = new HashSet<Friend>();
this.Photos = new HashSet<Photo>();
}
public int UserId { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public System.DateTime Birthday { get; set; }
public string ProfileImage { get; set; }
public string AboutUser { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Friend> Friends { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Friend> Friends1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Photo> Photos { get; set; }
}
This is the PhotoModel
public class PhotoModel
{
[Required]
public HttpPostedFileBase PhotoFile { get; set; }
}
And this is what I am getting as a view now. This is my /Main/Create View
And this is my /Main/PhotoUpload View
Now I want to put this PhotoUpload view instead of ProfileImage thing inside my Create View. Where do I change this and how?

You should use a ViewModel as that's the recommended practice for transferring data to and from views, in this case you can do the following as #StephenMuecke commented
ViewModel
public class UserViewModel
{
public string Email { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public System.DateTime Birthday { get; set; }
public string ProfileImage { get; set; }
public string AboutUser { get; set; }
[Required]
public HttpPostedFileBase PhotoFile { get; set; }
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(UserViewModel model)
{
if (ModelState.IsValid)
{
AddUser(model);
SavePhoto(model.PhotoFile);
return RedirectToAction("Index");
}
return View(user);
}
private void SavePhoto(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var filePath = Server.MapPath("/Content/Users/Images");
string savedFileName = Path.Combine(filePath, fileName);
file.SaveAs(savedFileName);
}
}
private void AddUser(UserViewModel model)
{
var user = new User
{
Email = model.Email, Password = model.Password, FirstName = model.FirstName, LastName = model.LastName, Gender = model.Gender, Birthday = model.Birthday, ProfileImage = model.ProfileImage, AboutUser = model.AboutUser
};
db.Users.Add(user);
db.SaveChanges();
}
For further reading:
http://www.mikesdotnetting.com/article/188/view-model-design-and-use-in-razor-views
http://rachelappel.com/use-viewmodels-to-manage-data-amp-organize-code-in-asp-net-mvc-applications/

Related

How we add foreign key in asp.net identity MVC Project

ApplicationUser Class which inherit with IdentityUser
public class ApplicationUser : IdentityUser
{
public DateTime BirthDate { get; set; }
public string User_type { get; set; }
public DateTime CreatedOn { get; set; }
public Enums.Sex Gender { get; set; }
public bool IsActive { get; set; }
public virtual Patient Patients { get; set; }
public int PatientID { get; set; }
}
Patient Class
public class Patient
{
[Key]
public int PatientID { get; set; }
public string ProfilePicture { get; set; }
public string FName { get; set; }
public DateTime BirthDate { get; set;}
public string City { get; set; }
public string Country { get; set; }
}
Controller
public async Task<ActionResult> RegisterPatient(RegisterViewModel model)
{
MYDb db = new MYDb();
Patient pt = new Patient();
pt.BirthDate = model.BirthDate;
pt.City = model.City;
pt.Country = model.Country;
pt.ProfilePicture = model.ProfilePicture;
pt.FName = model.FName;
int Pat_id = model.PatientID;
if (ModelState.IsValid)
{
ApplicationUser myuser = new ApplicationUser();
model.CreatedOn = DateTime.Now;
model.IsActive = true;
myuser.PatientID = Pat_id;
if (ModelState.IsValid)
{
var user = model.GetUser();
db.Patients.Add(pt);
db.SaveChanges();
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var idManager = new IdentityManager();
idManager.AddUserToRole(user.Id, model.User_type);
//await db.SaveChangesAsync();
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
return RedirectToAction("Index", "Home");
}
// If we got this far, something failed, redisplay form
return View();
}
i want to make relationship b/w Patient and ApplicationUser first i
add record in patient then "Patient_ID" used as a foreign key in
ApplicationUser Table but when add data i face this type of error
Error
Note : data save in Patient table but not in ApplicationUser table because ApplicationUser not get "PatientID" therefore conflict occurred in DB.
I hope this is much clear and its not easy to solve :(
In Applicatin User Model Write done this :
public class ApplicationUser : IdentityUser
{
public DateTime BirthDate { get; set; }
public string User_type { get; set; }
public DateTime CreatedOn { get; set; }
public Enums.Sex Gender { get; set; }
public bool IsActive { get; set; }
[ForeignKey("PatientID")]
public virtual Patient Patients{ get; set; }
}
I think it will work.

Access ViewModel fields in Edit view

My Model:
public ECmain()
{
this.Notes = new Collection<Notes>();
}
public int ID { get; set; }
public string Auth { get; set; }
public string KeyWords { get; set; }
public string Description { get; set; }
public string URL { get; set; }
public string Category { get; set; }
public string SubCategory { get; set; }
public string Title { get; set; }
public string Live { get; set; }
public virtual ICollection<Notes> Notes { get; set; }
public virtual ICollection<Email> Email { get; set; }
}
public class MyViewModel
{
public IQueryable<Notes> NotesList { get; set; }
public IQueryable<ECmain> ECmainList { get; set; }
public int ECmain.ID { get; set; }
public IQueryable<Email> EmailList { get; set; }
}
My Controller:
// GET: ECmain/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var viewModel = new MyViewModel
{
ECmainList = from m in db.ECmain.Take(10)
where m.ID == id
select m,
NotesList = from n in db.Notes
where n.ECmainID ==id
select n,
EmailList = from e in db.Email
where e.ECmainID ==id
select e
};
// viewModel.NotesList = new
if (viewModel == null)
{
return HttpNotFound();
}
return View(viewModel);
}
My Edit View:
#model EditSuite.Models.MyViewModel
#using (Html.BeginForm())
{
#Html.HiddenFor(model => model.ID )
I want to access the ECmainList.ID The error is
Compiler Error Message: CS1061: 'EditSuite.Models.MyViewModel' does not contain a definition for 'ID'
I tried
#Html.HiddenFor(model => model.ECmainListID.ID )
and
#Html.HiddenFor(Model.model.ECmainListID.ID )
Neither one worked.
It seems pretty obvious from the compiler message:
Compiler Error Message: CS1061: 'EditSuite.Models.MyViewModel' does not contain a definition for 'ID'
So where on the following model is the ID?:
public class MyViewModel
{
public IQueryable<Notes> NotesList { get; set; }
public IQueryable<ECmain> ECmainList { get; set; }
public IQueryable<Email> EmailList { get; set; }
// there is no: public int ID { get; set; } ?
}
I want to access the ECmainList.ID
However, per your model the ECmainList is a IQueryable<ECmain> and the IQueryable<T> also does not have a public property or field called ID. How can you add an editor for a ID of a list of objects? You'd need to loop through the list and have multiple ID fields.

MVC Updates over values with NULL

This is probably very simple for most MVC programmers, so maybe you can help me out. I have a table called Images in the database with nine columns. On my UPDATE, I just have three I want to mess with (ImageName, ImagePath, CourseID). After I post back with UPDATE, it sets the other six columns to NULL. I'm not sure how to handle this in MVC.:
My ViewModel:
public class GalleryViewModel
{
public Image _image { get; set; }
}
My Model:
public partial class Image
{
public int ImageID { get; set; }
public string ImageName { get; set; }
public string ImagePath { get; set; }
public Nullable<int> CourseID { get; set; }
public string UserId { get; set; }
public Nullable<System.DateTime> CreateDate { get; set; }
public string ImageType { get; set; }
public string ImageSize { get; set; }
public string FriendlyName { get; set; }
public virtual Cours Cours { get; set; }
}
My Controller:
[HttpGet]
public ActionResult UploadImageEdit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var model = new GalleryViewModel
{
_image = db.Images.Find(id),
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadImageEdit(GalleryViewModel galleryViewModel)
{
if (ModelState.IsValid)
{
db.Entry(galleryViewModel._image).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("UploadImageIndex");
}
return View(galleryViewModel);
}
After reading other examples and becoming more familiar with ViewModel to controller, I got the UPDATE to work by doing the following:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadImageEdit(int id, GalleryViewModel galleryViewModel)
{
if (ModelState.IsValid)
{
var imageContext = db.Images.Find(id);
imageContext.FriendlyName = galleryViewModel._image.FriendlyName;
db.Entry(imageContext).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("UploadImageIndex");
}
return View(galleryViewModel);
}
I hope this helps other folks out!

"A data source must be bound before this operation can be performed"

I am trying to display a grid in the MVC 3,
I got the following error:
A data source must be bound before this operation can be performed.
this is my Model:
public class EmpModel
{
public string UserName { get; set; }
public string Password { get; set; }
public int EmpID { get; set; }
public string EName { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
public string Qualification { get; set; }
public string Address { get; set; }
public string EmailID { get; set; }
public int DeptID { get; set; }
public string DeptName { get; set; }
public string DeptHead { get; set; }
public int Deptnumber { get; set; }
}
This is Controller:
TestMVCEntities testEmp = new TestMVCEntities();
EmpModel empmod = new EmpModel();
public ActionResult Index()
{
List<EmpModel> emp = new List<EmpModel>();
return View();
}
This is my View:
#model IEnumerable<EmpApplication.Models.EmpModel>
#{
ViewBag.Title = "Index";
WebGrid grid = new WebGrid();
}
<h2>List of Employee</h2>
#grid.GetHtml(columns: new [] {
grid.Column("EmpID"),
grid.Column("EName"),
grid.Column("EmailID"),
grid.Column("Qualification")
})
You must pass as parameter the source of your data. The WebGrid expects a IEnumerable<Object> or IEnumerable<dynamic> as source.
You must return the list to your view:
public ActionResult Index()
{
List<EmpModel> emp = new List<EmpModel>();
return View(emp);
}
Then pass it to WebGrid constructor:
#{
ViewBag.Title = "Index";
WebGrid grid = new WebGrid(Model);;
}
I'm sure it's works..
public ActionResult Index()
{
List<EmpModel> emp = new List<EmpModel>();
return View(emp.AsEnumerable());
}
You just change your retrun list as enumerable.

MVC Automapper update

i tried to update my database table some fields
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(MemberTasks membertaskdetails)
{
if (ModelState.IsValid)
{
MemberTasks Mtasks = db.MemberTask.Find(membertaskdetails.id);
Mtasks.Taskid = membertaskdetails.Taskid;
Mtasks.status = membertaskdetails.status;
AutoMapper.Mapper.Map(membertaskdetails,Mtasks);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(membertaskdetails);
}
ViewModel
public class MemberTasks
{
[Key]
[Display(Name = "ID")]
public int id { get; set; }
[Display(Name = "Task ID")]
public int Taskid { get; set; }
[Display(Name = "Status")]
public int status { get; set; }
[Display(Name = "Created By")]
public string createdby { get; set; }
[Display(Name = "Team Lead")]
public string TeamLead { get; set; }
[Display(Name = "Note")]
public string Note { get; set; }
[Display(Name = "Members")]
public string Membersid { get; set; }
}
Code is executed successfully but the problem is remaining fields also updated with null value i have 6 columns i want to update 2 columns only.
Any help ?
Your source and destination object used in AutoMapper are of the same type (MemberTasks). That's not how AutoMapper is supposed to be used. AutoMapper is used to map between domain models and view models.
So you must have a view model containing the properties passed from the view:
public class MemberTasksViewModel
{
public int Id { get; set; }
public int Taskid { get; set; }
public int Status { get; set; }
}
and then:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(MemberTasksViewModel viewModel)
{
if (ModelState.IsValid)
{
MemberTasks domainModel = db.MemberTask.Find(viewModel.Id);
Mapper.Map(viewModel, domainModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel);
}

Resources