For a school assignment I need to make a poll with ASP.NET
The problem I get when trying to write the answers in the database is that only one question and one answer gets written into it.
This is the View
#model CinemaJamV2.WebUIV2.Models.EnqueteModel
#{
ViewBag.Title = "Enquete";
}
<h2>Enquete</h2>
#Html.ValidationSummary(true)
#using (Html.BeginForm("Enquete", "Enquete", new { vraag = "vraag", antwoord = "antwoord", naam = "naam", cijfer = "cijfer" }))
{
<div class="col-md-12">
#for(var i=0;i< Model.enquetevragen.Count();i++)
{
<div class="thumbnail">
#Html.LabelFor(model => model.enquetevragen[i].vraag, new { htmlAttributes = new { #class = "form-control" } })
#Html.EditorFor(model => model.enquete.antwoord, new { htmlAttributes = new { #class = "form-control" } })
#Html.EditorFor(model => model.enquete.cijfer, new { htmlAttributes = new { #class = "form-control" } })
</div>
}
</div>
<div class="col-md-12">
<p>Naam <input type="text" name="naam" /> </p>
<input type="submit" name="submit" value="Verzend" />
</div>
}
This is the Controller:
namespace CinemaJamV2.WebUIV2.Controllers
{
public class EnqueteController : Controller
{
private IRepository<Enquete> repository;
private IRepository<EnqueteVraag> a_repository;
private CineJamContext db = new CineJamContext();
public EnqueteController(IRepository<Enquete> a_model, IRepository<EnqueteVraag> vraag_model)
{
repository = a_model;
a_repository = vraag_model;
}
[HttpGet]
public ActionResult Enquete()
{
EnqueteModel enquetevragen = new EnqueteModel
{
enquetevragen = a_repository.List
};
return View(enquetevragen);
}
[HttpPost]
public ActionResult Enquete(Enquete enquete)
{
if (ModelState.IsValid)
{
db.Enquetes.Add(enquete);
db.SaveChanges();
return RedirectToAction("Enquete");
}
return View(enquete);
}
}
}
The ModelView:
namespace CinemaJamV2.WebUIV2.Models
{
public class EnqueteModel
{
public List<Enquete> enquetes {get; set;}
public Enquete enquete { get; set; }
public List<EnqueteVraag> enquetevragen { get; set; }
}
}
And this is the Model Enquete which should contain all the given answers:
namespace CinemaJamV2.Domain.Entities
{
[Table("Enquete")]
public partial class Enquete : IEntity
{
public int Id { get; set; }
[StringLength(1000)]
public string vraag { get; set; }
[StringLength(1000)]
//[Required]
public string antwoord { get; set; }
public int? cijfer {get; set;}
[StringLength(50)]
//[Required]
public string naam { get; set; }
}
}
This Model contains all the Questions
namespace CinemaJamV2.Domain.Entities
{
[Table("EnqueteVraag")]
public partial class EnqueteVraag : IEntity
{
public int Id { get; set; }
[StringLength(1000)]
public string vraag { get; set; }
}
}
The action for POST has only one instance of the Model as its parameter. You need to read this: Model binding to a list
YOu need to use view model that will have list of Enquete and then in post method again you need to do for loop and save it to database.
See following links for samples.
http://www.binaryintellect.net/articles/b1e0b153-47f4-4b29-8583-958aa22d9284.aspx
http://www.c-sharpcorner.com/UploadFile/pmfawas/Asp-Net-mvc-how-to-post-a-collection/
http://www.codeproject.com/Tips/855577/List-of-Model-Object-Post-to-Controller-in-ASP-NET
Related
I am using EF and my relationship between tables is many-to-many. I want to display and edit the ICollection property to not only display my ingredients from a recipe, but to also edit, add, or delete them.
I tried to use EditorFor, but the changes of the ingredient were never changed and submitted to the database. I want to use DropDownList because it can show the ingredients that my recipe has in a list format so I can choose between them.
This is my Recipe and Ingredients Model with the relational table RecipesIngredients:
namespace Licenta.Models
{
public class Recipe
{
[Key]
public int IDRecipe { get; set; }
public string Name { get; set; }
public string Desc { get; set; }
public string Steps { get; set; }
public float Kcal { get; set; }
public float Pro { get; set; }
public float Carbo { get; set; }
public float Fat { get; set; }
public virtual ICollection<RecipesIngredients> RecipesIngredients { get; set; }
}
}
namespace Licenta.Models
{
public class RecipesIngredients
{
[Key]
[Column(Order = 1)]
public int IDRecipe { get; set; }
[Key]
[Column(Order = 2)]
public int IDIngredient { get; set; }
public virtual Recipe Recipe { get; set; }
public virtual Ingredient Ingredient { get; set; }
}
}
namespace Licenta.Models
{
public class Ingredient
{
[Key]
public int IDIngredient { get; set; }
public string Nume { get; set; }
public float Kcal { get; set; }
public float Pro { get; set; }
public float Carbo { get; set; }
public float Fat { get; set; }
public virtual ICollection<RecipesIngredients> RecipesIngredients { get; set; }
}
}
This is my Controller:
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Recipe recipe = db.Recipes.Find(id);
if (recipe == null)
{
return HttpNotFound();
}
return View(recipe);
}
// POST: Recipes/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "IDRecipe,Name,Kcal,Pro,Carbo,Fat,Desc,Steps,Ingredients,RecipesIngredients")] Recipe recipe)
{
if (ModelState.IsValid)
{
db.Entry(recipe).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(recipe);
}
And the View of the Edit page:
#model Licenta.Models.Recipe
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Rețetă</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.IDRecipe)
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#foreach (var item in Model.RecipesIngredients)
{
<td>
#Html.DropDownListFor(model => item.Ingredient.Nume, #* this is where i want to edit the ingredients*#)
</td>
}
<div class="col-md-10">
#Html.ValidationMessageFor(model => model.RecipesIngredients, "", 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>
}
That is the View that I want to use to edit my ingredients. Is there any way to do that?
I am getting values from a ViewModel into a view for form fields. In one of my DropDownList the values are correct but in another the value repeats itself instead of changing. What am I doing wrong?
ViewModel:
namespace FulfillmentPortal.ViewModels
{
public class ViewModel
{
[Required(ErrorMessage = "Please select a carrier")]
public List<Carrier> CarrierList { get; set; }
[Required(ErrorMessage = "Please select a service")]
public List<CarrierService> ServiceList { get; set; }
}
}
Controller:
public class FulfillmentController : Controller
{
private CarrierModel db = new CarrierModel();
// GET: Fulfillment
public ActionResult Index()
{
ViewModel vm = new ViewModel
{
CarrierList = db.Carriers.ToList(),
ServiceList = db.CarrierServices.ToList()
};
return View(vm);
}
}
View:
#model FulfillmentPortal.ViewModels.ViewModel
#{
ViewBag.Title = "index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="panel panel-primary">
<div class="panel-heading">REPORT OPTIONS</div>
<div class="panel-body" style="padding-left:35px;">
<form id="processForm" class="form-horizontal" action="~/Fulfillment/Report" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="sel1">Carrier:</label>
#Html.DropDownListFor(model => model.CarrierList, new SelectList(Model.CarrierList, "CarrierId", "CarrierName"), "Select a Carrier",
new { #class = "form-control", #style = "width:auto; margin-bottom:15px;" })
<label for="sel2">Carrier Services:</label>
#Html.DropDownListFor(model => model.ServiceList, new SelectList(Model.ServiceList, "Code", "WebName"), "Select a Service",
new { #class = "form-control", #style = "width:auto; margin-bottom:15px;" })
</div>
</form>
</div>
</div>
Model:
public partial class CarrierModel : DbContext
{
public CarrierModel()
: base("name=CarrierModel")
{
}
public virtual DbSet<Carrier> Carriers { get; set; }
public virtual DbSet<CarrierService> CarrierServices { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
[HttpPost]
public ActionResult Index(ViewModel viewModel)
{
if (ModelState.IsValid)
{
viewModel.CarrierList.ToList();
viewModel.ServiceList.ToList();
}
return View(viewModel);
}
This my controller now. Now my view is just erroring out. I think I am missing something or misunderstanding something.
DropDownListFor(model => model.ServiceList
This is not how this method is supposed to work, and I suspect this is the answer to your problem.
This lambda is supposed to provide a field that will hold a value that this drop down list outputs. For your case you should have two fields in the model:
public class ViewModel
...
public int CarrierId { get; set; }
public string CarrierServiceCode { get; set; }
These will hold currently selected value, on none if nothing is selected (yet). And they are supposed to be used in that lambda:
DropDownListFor(model => model.CarrierServiceCode
Alternatively you could use DropDownList() method, which does not require a field in the model, and give it a custom name that will be posted with selected value.
Your ViewModel should be as follows:
public class ViewModel
{
[Required(ErrorMessage = "Please select a carrier")]
public int CarrierId {get; set;}
[Required(ErrorMessage = "Please select a service")]
public int ServiceCode {get; set;}
public List<Carrier> CarrierList { get; set; }
public List<CarrierService> ServiceList { get; set; }
}
Then in the view:
<label for="sel1">Carrier:</label>
#Html.DropDownListFor(model => model.CarrierId, new SelectList(Model.CarrierList, "CarrierId", "CarrierName"), "Select a Carrier",
new { #class = "form-control", #style = "width:auto; margin-bottom:15px;" })
<label for="sel2">Carrier Services:</label>
#Html.DropDownListFor(model => model.ServiceCode, new SelectList(Model.ServiceList, "Code", "WebName"), "Select a Service",
new { #class = "form-control", #style = "width:auto; margin-bottom:15px;" })
Then your Index Post method should be as follows:
[HttpPost]
public ActionResult Index(ViewModel viewModel)
{
if(ModelState.IsValid)
{
// do whatever you want with `viewModel.CarrierId` and `viewModel.ServiceCode` here
}
viewModel.CarrierList = db.Carriers.ToList();
viewModel.ServiceList = db.CarrierServices.ToList();
return View(viewModel);
}
I am new to ASP.NET MVC and I'm trying to make simple app with many to many relationship (courses/students). In my language is (kurs/student).
This is my course class
namespace KurseviApp
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
public partial class Kurs
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Kurs()
{
this.Student = new HashSet<Student>();
}
public int PK_Kurs_ID { get; set; }
public string Naziv_Kursa { get; set; }
[NotMapped]
public string Izabrani { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Student> Student { get; set; }
}
}
This is my students class
namespace KurseviApp
{
using System;
using System.Collections.Generic;
public partial class Student
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Student()
{
this.Kurs = new HashSet<Kurs>();
}
public int PK_Student_ID { get; set; }
public string Broj_Indeksa { get; set; }
public string Ime { get; set; }
public string Prezime { get; set; }
public string Godina { get; set; }
public string Status { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Kurs> Kurs { get; set; }
}
}
And I have done it pretty well so far. But the problem appears when I am creating new course and selecting students for. This is my code in controller
private kurseviEntities db = new kurseviEntities();
public ActionResult Add(int id = 0)
{
Kurs ks = new Kurs();
using (db)
{
ks.Student = db.Student.ToList();
}
return View(ks);
}
[HttpPost]
public ActionResult Add(Kurs kurs)
{
using (db)
{
db.Student.Add(kurs); //THIS LINE IS A PROBLEM
db.SaveChanges();
}
return RedirectToAction("index");
}
It gives me error which I wrote in article title. If I delete the line, course is created successfully but I'm still missing adding students to course. Every help is welcome, thanks in advance.
EDIT: Here is my view
#model KurseviApp.Kurs
#{
ViewBag.Title = "Add";
}
<h2>Add</h2>
#using (Html.BeginForm())
{
<div class="form-horizontal">
#Html.HiddenFor(model => model.PK_Kurs_ID)
#Html.LabelFor(model => model.Naziv_Kursa, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Naziv_Kursa, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Naziv_Kursa, "", new { #class = "text-danger" })
</div>
<label>Odabir studenata</label>
#Html.DropDownListFor(model => model.Izabrani,
new SelectList(Model.Student, "PK_Student_ID", "Ime"),
new { #class="choosen-select", id = "normalDropDown" })
<input type="submit" name="name" value="submit" />
</div>
}
#section scripts {
<script>
$(function () {
$("#normalDropDown").chosen({ width: "15%" });
});
</script>
}
Kurs and Students are separate types of things; db.Students is a list of Students and you're trying to add a new Kurs into that list directly. My guess is that you want to get a specific student and then call student.Kurs.Add(kurs) to add the Kurs to the kurs list of the specific student.
I have a view model for a view AddAppointment. It has many properties of which 2 are Required (I wrote Required attribute over it).
Now I want to use the same model for another view but excluding the properties which are required but it doesn't work i.e. it's invalid.
What to do apart from writing another view model?
View Model:
public class AddBookingsViewModel
{
public string CustomerName { get; set; }
public string ContactNo { get; set; }
public string VehicleRegNo { get; set; }
public short fk_VehicleMakeID { get; set; }
public string VehicleModel { get; set; }
[Required(ErrorMessage = "Select appointment time ")]
public int fk_TimeSlotID { get; set; }
public byte fk_BookingModeID { get; set; }
public int EntryUserID { get; set; }
public int ReturnBookingID { get; set; }
[Required(ErrorMessage="Fill in the appointment date")]
[DataType(DataType.Date)]
public DateTime? AppointmentDate { get; set; }
}
View: (Where it is used)
#model ZahidCarWash.ViewModels.AddBookingsViewModel
#{
ViewBag.Title = "Add Appointment";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!-- page banner -->
<!-- end page banner -->
#using (Html.BeginForm())
{
<!-- appointments -->
<div id="appointments" class="appointment-main-block appointment-two-main-block">
<div class="container">
<div class="row">
<div class="section text-center">
<h3 class="section-heading text-center">Get an Appointment</h3>
</div>
<div class="col-md-8 col-sm-12">
<div class="appointment-block">
<h5 class="form-heading-title"><span class="form-heading-no">1.</span>Vehicle Information</h5>
<div class="row">
<div class="col-sm-4">
<div class="dropdown">
#Html.DropDownListFor(Model => Model.fk_VehicleMakeID, new SelectList(ZahidCarWash.DAL.VehicleMakesRepository.getVehicleMakes(), "VehicleMakeID", "MakeTitle"),
new { #class = "form-control" })
</div>
</div>
<div class="col-sm-4">
#Html.EditorFor(Model => Model.VehicleModel, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Vehicle Model" } })
</div>
<div class="col-sm-4">
#Html.EditorFor(Model => Model.VehicleRegNo, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Vehicle Reg No." } })
</div>
</div>
<h5 class="form-heading-title"><span class="form-heading-no">2.</span>Contact Details</h5>
<div class="row">
<div class="col-sm-4">
#Html.EditorFor(Model => Model.CustomerName, new { htmlAttributes = new { #class = "form-control", placeholder = "Customer Name" } })
#Html.ValidationMessageFor(Model => Model.CustomerName, "", new { #class = "ErrorMessages" })
</div>
<div class="col-sm-4">
#Html.EditorFor(Model => Model.ContactNo, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Contact Number." } })
#Html.ValidationMessageFor(Model => Model.ContactNo, "", new { #class = "ErrorMessages" })
</div>
</div>
<button type="submit" class="btn btn-default pull-right">Book Now</button>
</div>
</div>
</div>
</div>
</div>
}
Controller:
public JsonResult AddManualAppointment(AddBookingsViewModel AddBookingVM)
{
if (ModelState.IsValid)
{
AddBookingVM.fk_BookingModeID = 2;
int ReturnRowsCount = BookingRep.InsertCustomerAppointments(AddBookingVM, out ReturnStatus, out ReturnMessage, out ReturnBookingID);
}
else
{
}
return Json(new { ReturnMessageJSON = ReturnMessage, ReturnStatusJSON = ReturnStatus });
}
Data is passed through ajax:
<script type="text/javascript">
//to add an appointment
$('form').submit(function (e) {
e.preventDefault();
if (!$(this).valid()) {
return;
}
var url = '#Url.Action("AddManualAppointment")';
var data = $(this).serialize();
$.post(url, data, function (response) {
if (response.ReturnStatusJSON == true) {
swal("Booked !", response.ReturnMessageJSON, "success");
$("#VehicleRegNo").val("");
$("#VehicleModel").val("");
$("#CustomerName").val("");
$("#ContactNo").val("");
}
else {
swal("Sorry !", response.ReturnMessageJSON, "error");
}
});
});
</script>
<!--End Custom Scripts-->
}
I guess the quick and dirty way is to use #Html.Hiddenfor and fill the value with a new datetime from inside your controller
You can split your view model into a version with and without the required attributes using inheritance:
public class AddBookingsViewModel
{
public string CustomerName { get; set; }
public string ContactNo { get; set; }
public string VehicleRegNo { get; set; }
public short fk_VehicleMakeID { get; set; }
public string VehicleModel { get; set; }
public byte fk_BookingModeID { get; set; }
public int EntryUserID { get; set; }
public int ReturnBookingID { get; set; }
}
public class AddBookingsViewModelWithAppointment : AddBookingsViewModel
{
[Required(ErrorMessage = "Select appointment time ")]
public int fk_TimeSlotID { get; set; }
[Required(ErrorMessage="Fill in the appointment date")]
[DataType(DataType.Date)]
public DateTime? AppointmentDate { get; set; }
}
This allows you to use the appropriate view model in your situation and still maintain compatibilty through polymorphism.
If you need the optional properties in your base class, you can make your properties virtual and apply the attribute in the derived class:
public class AddBookingsViewModel
{
public string CustomerName { get; set; }
public string ContactNo { get; set; }
public string VehicleRegNo { get; set; }
public short fk_VehicleMakeID { get; set; }
public string VehicleModel { get; set; }
public byte fk_BookingModeID { get; set; }
public int EntryUserID { get; set; }
public int ReturnBookingID { get; set; }
public virtual int fk_TimeSlotID { get; set; }
public virtual DateTime? AppointmentDate { get; set; }
}
public class AddBookingsViewModelWithAppointment : AddBookingsViewModel
{
[Required(ErrorMessage = "Select appointment time ")]
public override int fk_TimeSlotID {
get => base.fk_TimeSlotID;
set => base.fk_TimeSlotID = value;
}
[Required(ErrorMessage="Fill in the appointment date")]
[DataType(DataType.Date)]
public override DateTime? AppointmentDate {
get => base.AppointmentDate;
set => base.AppointmentDate = value;
}
}
Use the veriant that works best in your business case.
I have a page that show details of a post and Identified users can add commented on that post.
My problems:
PostID and UserID is FK in Comment model and don't pass from view to controller
CommnetMessage is Null!!
what is wrong?
Comment Model :
public class Comment : System.Object
{
public Comment()
{
this.CommnetDate = General.tzIran();
}
[Key]
public int CommentID { get; set; }
[Required]
public string CommnetMessage { get; set; }
[Required]
public DateTime CommnetDate { get; set; }
public string UserId { get; set; }
[Key, ForeignKey("UserId")]
public virtual ApplicationUser ApplicationUser { get; set; }
public int PostID { get; set; }
[Key, ForeignKey("PostID")]
public virtual Post posts { get; set; }
}
Post Model:
public class Post : System.Object
{
public Post()
{
this.PostDate = General.tzIran();
this.PostViews = 0;
}
[Key]
public int PostID { get; set; }
public string PostName { get; set; }
public string PostSummery { get; set; }
public string PostDesc { get; set; }
public string PostPic { get; set; }
public DateTime PostDate { get; set; }
public int PostViews { get; set; }
public string postMetaKeys { get; set; }
public string PostMetaDesc { get; set; }
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser ApplicationUser { get; set; }
public int CategoryID { get; set; }
[ForeignKey("CategoryID")]
public virtual Category Category { get; set; }
public virtual ICollection<Comment> commnets {get; set;}
}
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
/*Realations*/
public virtual ICollection<Comment> Comments { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
View Model:
public class PostViewModel
{
public ApplicationUser Users { get; set; }
public Post posts { get; set; }
public Category Categories { get; set; }
public IEnumerable<Comment> ListCommnets { get; set; }
public Comment Commnets { get; set; }
}
Controller:
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var post = db.Posts.Find(id);
post.PostViews += 1;
db.SaveChanges();
if (post == null)
{
return HttpNotFound();
}
return View(new PostViewModel() { posts = post });
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details([Bind(Include = "CommentID,CommnetMessage,CommnetDate,UserId,PostID")] Comment comment , int? id)
{
int pid = comment.PostID;
if (ModelState.IsValid)
{
db.CommentS.Add(comment);
db.SaveChanges();
TempData["notice"] = "پیغام شما با موفقیت ثبت شد.";
return RedirectToAction("success");
}
ViewBag.UserId = new SelectList(db.Users, "Id", "FirstName", comment.UserId);
ViewBag.PostID = id;
return View( new PostViewModel() { posts = db.Posts.Find(id)});
}
public ActionResult success()
{
ViewBag.Message = "از طریق فرم زیر می توانید برایمان پیغام بگذارید.";
return View("Details", new PostViewModel() { ListCommnets = db.CommentS });
}
Comment Partial View:
#using Microsoft.AspNet.Identity
#using FinalKaminet.Models
#using Microsoft.AspNet.Identity.EntityFramework
#model FinalKaminet.ViewModel.PostViewModel
#if (TempData["notice"] != null)
{
<p>#TempData["notice"]</p>
}
#if (Request.IsAuthenticated)
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = manager.FindById(User.Identity.GetUserId());
using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.posts.PostID)
#Html.HiddenFor(model => model.Users.Id)
<div class="form-group">
#Html.LabelFor(model => model.Users.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#{
var name = user.FirstName + " " + user.LastName;
}
<input type="text" id="Id" value="#name" disabled="disabled" class="form-control" />
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Commnets.CommnetMessage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Commnets.CommnetMessage, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Commnets.CommnetMessage, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Send" class="btn btn-default" />
</div>
</div>
</div>
}
}
else
{
<p>#Html.ActionLink("Log in", "Login", "Account", new { returnUrl = Request.Url }, null)</p>
}
As #StephenMuecke stated, model of your view is PostViewModel and all editors, hidden fields are created based on your view model. For example, when you generate hidden field using #Html.HiddenFor(model => model.posts.PostID) and try to post your data MVC model binder tries to bind the value of this field to the model specified at your Action method. In your case it is Comment so , MVC model binder will try bind value of generated hidden field to Comment.posts.PostID which does not exist. To make everything work perfectly you have to use same view model as a argument of your action method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details(PostViewModel viewModel)
{
......
}
Also, again as #StephenMuecke sated, your view model should have only those properties which you need. For example, your PostViewModel should look like something as following:
public class PostViewModel
{
// Actually, you do not need UserId property
// as it should be retrieved inside controller
// from current user data
public string UserId { get; set; }
public string UserName { get; set; }
public int PostID { get; set; }
public string CommentMessage { get; set; }
}
Back to your action method, you have to map view model to your model:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details(PostViewModel viewModel)
{
Comment comment = new Comment
{
CommnetMessage = viewModel.CommentMessage,
// and other properties
}
// Save your model and etc.
}