Capturing date time from the view into the database MVC - c#

I created MVC application that has a text box posted to the database. When the text box is posted, I want to capture today's date from the view and store it into the table. How do I capture the date and time the view that posted and how do I pass this information into row Date within the database? Appreciate any help.
Controller
[HttpGet]
public ActionResult Pay(int accountNumber)
{
return View();
}
[HttpPost]
public ActionResult Pay(Payments payment )
{
if(ModelState.IsValid)
{
DB.Payment.Add(payment);
DB.SaveChanges();
var service = new Accounts(DB);
service.Updatepayee(payment.AccountNumber);
return RedirectToAction("Index", "Home");
}
return View();
}
Payments Class
public class Payments
public int Id { get; set; }
[Required]
[DataType(DataType.Currency)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public decimal Amount { get; set; }
[Required]
public int AccountNumber {get; set;}
[RegularExpression(#"(^$)|(^\d{2}/\d{2}/\d{4})|(^((\d{1})|(\d{2}))/((\d{1})|(\d{2}))/(\d{4})\s((\d{1})|(\d{2}))[:]{1}((\d{1})|(\d{2}))[:]{1}((\d{1})|(\d{2}))\s((AM)|(PM)))", ErrorMessage = "Invalid Date")]
public DateTime TransactionDate { get; set; }
//Navigation property to check the account
public virtual AccountNumber accountNumber { get; set; }
}
Pay View
#model Credits.View.Payments
#{
ViewBag.Title = "Pay"; }
<h2>Payments</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Transaction</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Amount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Amount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Amount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div> }
<div>
#Html.ActionLink("Back to List", "Index", "Home") </div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval") }

Couldn't you set it in the controller:
[HttpPost]
public ActionResult Pay(Payments payment )
{
if(ModelState.IsValid)
{
payment.TransactionDate = DateTime.Now.ToUniversalTime();
DB.Payment.Add(payment);
DB.SaveChanges();

[HttpPost]
public ActionResult Pay(Payments payment )
{
var d=DateTime.Now.ToUniversalTime();
if(ModelState.IsValid)
{
Payments p=new() Payments{
AccountNumber=p.AccountNumber,
Amount=payment.Amount,
TransactionDate=d
};
DB.Payment.Add(p);
DB.SaveChanges();

Related

New to this error: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[]

I am quite new to ASP.NET MVC and C#. My final year project requires me to do a web app using ASP.NET MVC c#. I would really appreciate if you could help this newbie.
I have been getting this error and I can't seem to figure out the error or how to fix it:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[test2.Models.UsersModel]', but this dictionary requires a model item of type 'test2.Models.user_account'.
Here's my Controller:
using System.Net;
using System.Web;
using System.Web.Mvc;
using test2.Models;
using System.Runtime.InteropServices;
using System.Net.Http;
using System.Runtime.InteropServices.WindowsRuntime;
namespace test2.Controllers
{
//Admin page show be able to manage role
public class AdminController : Controller
{
public ActionResult Index() {
ubdcsEntities dc = new ubdcsEntities();
var userRoles = (from user in dc.user_account
select new {
UserId = user.userID,
Username = user.username,
EmailID = user.emailID,
RoleName = (from userRole in dc.userRoles
join role in dc.role1 on userRole.roleID
equals role.roleID
select role.roleName).ToList()
}).ToList().Select(p => new UsersModel()
{
Username = p.Username,
EmailID = p.EmailID,
RoleName = p.RoleName.ToString()
}).ToList();
return View(userRoles);
}
}
}
My Index - Yes I was trying to use a drop down for the roleName so that I can just assign the user's role from the drop down but it is not working
#model IEnumerable<test2.Models.UsersModel>
#{
ViewBag.Title = "Users With Roles";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="box-title">
<b>Users with Roles</b>
</h3>
</div>
<!-- /.box-header -->
<div class="panel-body">
<table class="table table-hover table-bordered table-condensed" id="UsersWithRoles">
<thead>
<tr>
<td><b>Username</b></td>
<td><b>Email</b></td>
<td><b>Roles</b></td>
</tr>
</thead>
#foreach (var user in Model)
{
<tr>
<td>#user.Username</td>
<td>#user.EmailID</td>
<td>
#user.RoleID
#*Html.DropDownListFor(user => user.FirstOrDefault().RoleName, new SelectList(new[]{"Admin","Student", "Counselor"}))*#
</td>
</tr>
}
</table>
</div>
<div class="panel-footer">
<p class="box-title"><b>Total Users till #String.Format("{0 : dddd, MMMM d, yyyy}", DateTime.Now) : </b><span class="label label-primary">#Model.Count()</span></p>
</div>
</div>
#section scripts{
<script>
$(function () {
$('#UsersWithRoles').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true
});
});
</script>
} v>
My model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace test2.Models
{
public partial class UsersModel
{
public int UserID { get; set; }
public string Username { get; set; }
public string EmailID { get; set; }
public int RoleID { get; set; }
public string RoleName { get; set; }
}
}
Below is model from the database (user_account)
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace test2.Models
{
using System;
using System.Collections.Generic;
public partial class user_account
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public user_account()
{
this.calendars = new HashSet<calendar>();
}
public int userID { get; set; }
public string username { get; set; }
public string emailID { get; set; }
public string password { get; set; }
public int roleID { get; set; }
public virtual user_emergency user_emergency { get; set; }
public virtual user_profile user_profile { get; set; }
public virtual user_record user_record { get; set; }
public virtual counselor_account1 counselor_account1 { get; set; }
public virtual userRole userRole { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<calendar> calendars { get; set; }
public virtual role1 role { get; set; }
}
}
View that uses #model.test2.models.user_account - user registration
#model test2.Models.user_account
#{
ViewBag.Title = "Signup";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Sign in</h2>
<div>
#using (Html.BeginForm("Signup", "Home"))
{
<div style="color:red;">#Html.ValidationSummary()</div>
<!--Show details are saved successfully message-->
<div class="col-lg-12">#ViewBag.Message</div>
<br />
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.username, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.username, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.username, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.emailID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.emailID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.emailID, "", new { #class = "text-danger" })
#Html.ValidationMessage("EmailExist", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Register" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Login", "Index", "Home")
</div>
</div>
#section Scripts{
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
}
The Home Controller
//Return Register view
[AllowAnonymous]
[HttpGet]
public ActionResult Signup()
{
return View();
}
[HttpPost]
//[ValidateAntiForgeryToken]
public ActionResult Signup(user_account user, int role_id)
{
//new code
var claims = new List<Claim>();
#region //Email already existt
var isExist = IsEmailExist(user.emailID);
if (isExist)
{
ModelState.AddModelError("EmailExist", "Email already exist");
return View(user);
}
#endregion
#region Password Hashing
user.password = Crypto.Hash(user.password);
user.ConfirmPassword = Crypto.Hash(user.ConfirmPassword);
#endregion
//We check if the model state is valid or not. We have used DataAnnotation attributes.
//If any form value fails the DataAnnotation validation the model state becomes invalid.
if (ModelState.IsValid)
{
#region Save to Database
using (ubdcsEntities db = new ubdcsEntities())
{
//If the model state is valid i.e. the form values passed the validation then we are storing the User's details in DB.
//Calling the SaveDetails method which saves the details.
claims.Add(new Claim(ClaimTypes.Role, role_id.ToString()));
db.user_account.Add(user);
db.SaveChanges();
}
#endregion
//showing succesfully registered page
ViewBag.Message = "User has successfully registered!";
return View();
}
else
{
//If the validation fails, we are returning the model object with errors to the view, which will display the error messages.
ViewBag.Message = "Invalid Request";
return View(user);
//return View("Signup", "Home", user);
}
}
[NonAction]
public bool IsEmailExist(string emailID)
{
using (ubdcsEntities dc = new ubdcsEntities())
{
var v = dc.user_account.Where(a => a.emailID == emailID).FirstOrDefault();
return v != null;
}
}

ASP.Net MVC Update entity met with "The entity could not be updated."

I'm fairly new to coding, and am trying to tie up the finishing touches to my personal MVC project. I have done breakpoints to see double-check that the types of the values I'm passing through are matching up, which I believe they are, but it's hard for me to navigate the breakpoints and understand what information I should be looking at.
When I do breakpoints, it skips the final If-statement shown below:
if (service.UpdatePromotion(model))
{
TempData["SaveResult"] = "The promotion has been updated!";
return RedirectToAction("Index");
}
If there is any other information needing to be posted, I'll update here if I can or in the comments. I really appreciate anyone who looks this over.
Controller
// GET: Edit
public ActionResult Edit(int id)
{
var service = CreatePromotionService();
var detail = service.GetPromotionById(id);
var model = new PromotionEdit
{
PromotionId = detail.PromotionId,
PromotionName = detail.PromotionName,
DateFounded = detail.DateFounded,
Website = detail.Website
};
return View(model);
}
// POST: Edit
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, PromotionEdit model)
{
if (!ModelState.IsValid) return View(model);
if (model.PromotionId != id)
{
ModelState.AddModelError("", "ID Mismatch");
return View(model);
}
var service = CreatePromotionService();
if (service.UpdatePromotion(model))
{
TempData["SaveResult"] = "The promotion has been updated!";
return RedirectToAction("Index");
}
ModelState.AddModelError("", "The promotion could not be updated.");
return View(model);
}
Services
public PromotionDetail GetPromotionById(int id)
{
using (var ctx = new ApplicationDbContext())
{
var entity = ctx.Promotions
.Single(e => e.PromotionId == id
&& e.OwnerId == _userId);
return new PromotionDetail
{
PromotionId = entity.PromotionId,
PromotionName = entity.PromotionName,
DateFounded = entity.DateFounded.Date,
Website = entity.Website,
CreatedUtc = entity.CreatedUtc
};
}
}
public bool UpdatePromotion(PromotionEdit model)
{
using (var ctx = new ApplicationDbContext())
{
var entity = ctx.Promotions.Single(e =>
e.PromotionId == model.PromotionId
&& e.OwnerId == _userId);
entity.PromotionName = model.PromotionName;
entity.IsStarred = model.IsStarred;
entity.DateFounded = model.DateFounded.Date;
entity.Website = model.Website;
return ctx.SaveChanges() == 1;
}
}
Model
public class PromotionDetail
{
[Display(Name = "Promotion ID")]
public int PromotionId { get; set; }
[Display(Name = "Promotion Name")]
public string PromotionName { get; set; }
[Display(Name = "Date Founded")]
public DateTime DateFounded { get; set; }
[Display(Name = "Website")]
public string Website { get; set; }
[Display(Name = "Date Created")]
public DateTimeOffset CreatedUtc { get; set; }
}
public class PromotionEdit
{
public int PromotionId { get; set; }
[Display (Name = "Promotion Name")]
public string PromotionName { get; set; }
public bool IsStarred { get; set; }
public DateTime DateFounded { get; set; }
public string Website { get; set; }
}
View
#model Models.PromotionEdit
#{
ViewBag.Title = "Edit";
}
<h2>Updating Promotion</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.PromotionId)
<div class="form-group">
#Html.LabelFor(model => model.PromotionName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PromotionName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PromotionName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DateFounded, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateFounded, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DateFounded, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Website, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Website, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Website, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div id="linkColor">
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Shout-out to curious.netter in the comments. I was being lazy with the update, not changing anything and clicking Submit. Since there were no changes to apply, the entity would not update, which would skip the last If statement.

File Upload Control Get Returned Null

Whenever i am clicking on submit after uploading file, it gets returned null, i have used all the necessary conditions required for upload file but still getting the issue, i have seen all the answers in stack overflow , i have used enctype and name of file upload is also same as what i am passing controller
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Officername,Designation,FileBeforeTour,FileAfterTour,FileBeforeTourName,FileAfterTourName")] FileDetails fileDetails)
{
if (ModelState.IsValid)
{
string uploadedfilename = Path.GetFileName(fileDetails.filebeforetourupload.FileName);
if (!string.IsNullOrEmpty(uploadedfilename))
{
db.FileUpload.Add(fileDetails);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(fileDetails);
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace OnlineStationaryRegister.Models
{
public class FileDetails
{
[Key]
public int FileId { get; set; }
public string Officername { get; set; }
public string Designation { get; set; }
public string FileBeforeTour { get; set; }
public string FileAfterTour { get; set; }
public string FileBeforeTourName { get; set; }
public string FileAfterTourName { get; set; }
[NotMapped]
public HttpPostedFileBase filebeforetourupload { get; set; }
[NotMapped]
public HttpPostedFileBase fileaftertourupload { get; set; }
}
}
#model OnlineStationaryRegister.Models.FileDetails
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create","File",FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>FileDetails</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Officername, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Officername, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Officername, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Designation, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Designation, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Designation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("File", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="filebeforetourupload" />
</div>
</div>
#*<div class="form-group">
#Html.LabelFor(model => model.FileAfterTour, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="fileaftertourupload" />
</div>
</div>*#
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Change your controllers method as,This will fix your issue
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(FileDetails fileDetails)
{
if (ModelState.IsValid)
{
string uploadedfilename =
Path.GetFileName(fileDetails.filebeforetourupload.FileName);
if (!string.IsNullOrEmpty(uploadedfilename))
{
db.FileUpload.Add(fileDetails);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(fileDetails);
}
Okay then this is what you should do. Instead of putting the HttpPostedFileBase field as part of the model, remove it from there and do this
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Officername,Designation,FileBeforeTour,FileAfterTour,FileBeforeTourName,FileAfterTourName")] FileDetails fileDetails, HttpPostedFileBase myFile)
{
}
then you can manipulate if from there. Sometimes the browser does not properly include files inside the model.

ModelState.IsValid always true

Visual Studio 2015 Update 1.
MVC 5.2.3.
.NET 4.5.2
It's picking up the Display Name ok, but it's not honoring the Required attribute, it would seem. Thanks!!!
View:
#model Insure.Entities.Policy
#{ ViewBag.Title = "Policy"; }
<h2>Policy</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Create</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.EffDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EffDate)
#Html.ValidationMessageFor(model => model.EffDate)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ExpDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ExpDate)
#Html.ValidationMessageFor(model => model.ExpDate)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Model:
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Insure.Entities
{
public class Policy
{
public int PolicyID { get; set; }
public Guid PolicyNumber { get; set; }
[Required(ErrorMessage = "Effective Date Required")]
[DataType(DataType.DateTime)]
[DisplayName("Effective Date")]
public DateTime EffDate { get; set; }
[Required(ErrorMessage = "Expiration Date Required")]
[DataType(DataType.DateTime)]
[DisplayName("Expiration Date")]
public DateTime ExpDate { get; set; }
}
}
Controller:
// POST: Policy/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(FormCollection collection)
{
try
{
if (ModelState.IsValid)
{
// TODO: Add logic to insert to DB
return RedirectToAction("Index");
}
else
{
return View();
}
}
catch
{
return View();
}
}
public ActionResult Create(FormCollection collection)
should be
public ActionResult Create(Policy myPolicyModel)
Then validation will be executed on the model.

ASP.NET MVC multiple models single set of Create, View, Edit and Delete pages

I have a problem figuring out how to implement the Create, Edit and Delete pages for a case where there are multiple Models that I want to display in a single set of Views.
I'm using Visual Studio 2013 and MVC 5. And I also use the latest Entity Framework 6.1.1.
So far I've got the Models:
public class CompositeModel
{
public int ID { get; set; }
public MediaPlan MediaPlanModel { get; set; }
public ContactInfo ContactInfoModel { get; set; }
public MediaPlanDate MediaPlanDateModel { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
public class MediaPlan
{
public int ID { get; set; }
public string Client { get; set; }
public string Product { get; set; }
public string AE { get; set; }
public string Supervisor { get; set; }
public string Traffic { get; set; }
}
public class ContactInfo
{
public int ID { get; set; }
public string CompanyName { get; set; }
public string CompanyContact { get; set; }
public string CompanyAddress { get; set; }
public string CompanyPhoneNumber { get; set; }
public string CompanyEmail { get; set; }
}
public class MediaPlanDate
{
public int ID { get; set; }
public string Client { get; set; }
public string Product { get; set; }
public string AE { get; set; }
public string Supervisor { get; set; }
public string Traffic { get; set; }
}
Using Code First approach the database was created correctly.
I did auto-generate the CompositeModelsController.cs:
public class CompositeModelsController : Controller
{
private MprContext db = new MprContext();
// GET: CompositeModels
public ActionResult Index()
{
//var compositeModel = new CompositeModel();
//compositeModel.MediaPlanModel = new MediaPlan();
//compositeModel.ContactInfoModel = new ContactInfo();
//compositeModel.MediaPlanDateModel = new MediaPlanDate();
//return View(compositeModel.ToList());
return View(db.Composites.ToList());
}
// GET: CompositeModels/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CompositeModel compositeModel = db.Composites.Find(id);
if (compositeModel == null)
{
return HttpNotFound();
}
return View(compositeModel);
}
// GET: CompositeModels/Create
public ActionResult Create()
{
return View();
}
// POST: CompositeModels/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 = "ID,RowVersion")] CompositeModel compositeModel)
{
if (ModelState.IsValid)
{
db.Composites.Add(compositeModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(compositeModel);
}
// GET: CompositeModels/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CompositeModel compositeModel = db.Composites.Find(id);
if (compositeModel == null)
{
return HttpNotFound();
}
return View(compositeModel);
}
// POST: CompositeModels/Edit/5
// 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 Edit([Bind(Include = "ID,RowVersion")] CompositeModel compositeModel)
{
if (ModelState.IsValid)
{
db.Entry(compositeModel).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(compositeModel);
}
// GET: CompositeModels/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CompositeModel compositeModel = db.Composites.Find(id);
if (compositeModel == null)
{
return HttpNotFound();
}
return View(compositeModel);
}
// POST: CompositeModels/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
CompositeModel compositeModel = db.Composites.Find(id);
db.Composites.Remove(compositeModel);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
I did not expect it to work and it doesn't.
I was able to get the Index to work.
I also created Editor Templates:
#model Online_Mpr.Models.MediaPlan
<h2>MediaPlan</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>MediaPlan</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.Client, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Product, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Product, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Product, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Supervisor, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Supervisor, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Supervisor, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Traffic, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Traffic, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Traffic, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
And so forth for the other Models.
Then I have the Create View:
#model Online_Mpr.Models.CompositeModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CompositeModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.EditorFor(model => model.MediaPlanModel)
#Html.EditorFor(model => model.MediaPlanDateModel)
#Html.EditorFor(model => model.ContactInfoModel)
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I was planning to do similar thing for the Edit View.
When I go to the Create View it displays the edit boxes for all the elements but how do I get to code the controller that will create the records in the database.
Preferably I would like to have just one "Create" button in the Create View that would create all four records.
Any help is appreciated as I scoured the internet for info about similar cases and could not find any.
Also if you could provide code samples. They don't have to be elaborate but the core thought will lead me on.
Thanks,
-Arek
Your CompositeModel is essentially a view model. This class shouldn't have an Id property and should n't actually be tied to Entity Framework in any way (don't add a DbSet for it). All it needs to do is contain properties for the other model instances that you want to edit. You should also add a constructor to this class that news up all other models inside:
public class CompositeModel
{
public CompositeModel()
{
MediaPlanModel = new MediaPlan();
ContactInfoModel = new ContactInfo();
MediaPlanDateModel = new MediaPlanDate();
}
...
}
Then in post version of your Create action. You'll simply save each sub-model individually:
[HttpPost]
public ActionResult Create(CompositeModel model)
{
if (ModelState.IsValid)
{
db.MediaPlans.Add(model.MediaPlanModel);
db.ContactInfos.Add(model.ContactInfoModel);
db.MediaPlanDates.Add(model.MediaPlanDateModel)
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
For your edit version:
[HttpPost]
public ActionResult Edit(CompositeModel model)
{
if (ModelState.IsValid)
{
db.Entry(model.MediaPlanModel).State = EntityState.Modified;
db.Entry(model.ContactInfoModel).State = EntityState.Modified;
db.Entry(model.MediaPlanDateModel).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}

Categories