I know this question has been asked and answered a dozen of times but none of the solutions help me.
I have a following ViewModel which is consisted of ProductDetail data model and a list of Product_ProductCategoryAttribute data model.
public class ProductDetailViewModel
{
public ProductDetail ProductDetail { get; set; }
public List<Product_ProductCategoryAttribute> Product_ProductCategoryAttribute { get; set; }
}
On an action postback I receive an empty ViewModel.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "idProductDetail,idProductCategory,idProduct,Name,Description")] ProductDetailViewModel productDetailAll)
{
if (ModelState.IsValid)
{
ProductDetail productDetail = productDetailAll.ProductDetail;
db.Entry(productDetail).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(productDetailAll);
}
However, as I believe that the underlying problem is somewhere within the view I will add the view code snippet.
#using (Html.BeginForm("Edit", "ProductDetail", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.HiddenFor(model => model.ProductDetail.idProductDetail)
<div class="form-group">
#Html.LabelFor(model => model.ProductDetail.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.ProductDetail.Name, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductDetail.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.ProductDetail.Description, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
#for (int i = 0; i < Model.Product_ProductCategoryAttribute.Count(); i++)
{
<div class="form-group">
<label class="control-label col-md-2">#Model.Product_ProductCategoryAttribute[i].ProductCategoryAttribute.Name</label>
<div class="col-md-5">
#Html.TextBoxFor(model => model.Product_ProductCategoryAttribute[i].Value, new { #class = "form-control" })
</div>
</div>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-sm btn-default" />
</div>
</div>
</div>
}
HTML generated from the view above is as follows (some parts are ommited for brevity):
<form action="/Administration/ProductDetail/Edit/4" method="post"><input name="__RequestVerificationToken" type="hidden" value="IS4fstTTjOD4d9FEzyM5yWlvO9xqlOq_AHFx_8_vC079F1iDvucf5wgRIgV4iXH-NGU-u-J8IHBiKT4ApvR3cSLbhw_AntbibEFsD68eUkc1" />
<input data-val="true" data-val-number="The field idProductDetail must be a number." data-val-required="The idProductDetail field is required." id="ProductDetail_idProductDetail" name="ProductDetail.idProductDetail" type="hidden" value="4" />
<div class="form-group">
<label class="control-label col-md-2" for="ProductDetail_Name">Name</label>
<div class="col-md-10">
<input htmlAttributes="{ class = form-control }" id="ProductDetail_Name" name="ProductDetail.Name" type="text" value="Čipka i hiljadu šara" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="ProductDetail_Description">Description</label>
<div class="col-md-10">
<input htmlAttributes="{ class = form-control }" id="ProductDetail_Description" name="ProductDetail.Description" type="text" value="Šipka i čipka" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Veličina</label>
<div class="col-md-5">
<input class="form-control" id="Product_ProductCategoryAttribute_0__Value" name="Product_ProductCategoryAttribute[0].Value" type="text" value="" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Širina</label>
<div class="col-md-5">
<input class="form-control" id="Product_ProductCategoryAttribute_1__Value" name="Product_ProductCategoryAttribute[1].Value" type="text" value="" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Pakiranje</label>
<div class="col-md-5">
<input class="form-control" id="Product_ProductCategoryAttribute_2__Value" name="Product_ProductCategoryAttribute[2].Value" type="text" value="" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-sm btn-default" />
</div>
</div>
</div>
I'm not sure if something is wrong with the naming convention but my bet would be on that.
The problem was in autogenerated controller Edit action which added couple of [Bind(Include="")] attributes which were wrong and which were preventing data to be posted to the server.
Correct snippet would look like this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit (ProductDetailViewModel productDetailAll)
{
if (ModelState.IsValid)
{
ProductDetail productDetail = productDetailAll.ProductDetail;
db.Entry(productDetail).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(productDetailAll);
}
Related
So here is my view page
#model RandApp.Models.Item
#{
ViewBag.DesignedList = Enum.GetValues(typeof(RandApp.Enums.DesignedFor)).Cast<RandApp.Enums.DesignedFor>().ToList();
ViewBag.CategoryList = Enum.GetValues(typeof(RandApp.Enums.Category)).Cast<RandApp.Enums.Category>().ToList();
ViewBag.ItemColorList = Enum.GetValues(typeof(RandApp.Enums.ItemColor)).Cast<RandApp.Enums.ItemColor>().ToList();
ViewBag.ItemSizeList = Enum.GetValues(typeof(RandApp.Enums.ItemSize)).Cast<RandApp.Enums.ItemSize>().ToList();
ViewBag.MaterialTypeList = Enum.GetValues(typeof(RandApp.Enums.MaterialType)).Cast<RandApp.Enums.MaterialType>().ToList();
var selectedDesignedFor = "";
var selectedCategory = "";
}
<h4>Add Item</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="CreateItem" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="#Model.ItemPhoto" class="control-label"></label>
<input type="file" name="ItemPhoto" class="form-control-file" onchange="SetValue(this)" />
<input asp-for="#Model.ItemPhoto" hidden />
<span asp-validation-for="#Model.ItemPhoto" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Name" class="control-label"></label>
<input asp-for="#Model.Name" class="form-control" />
<span asp-validation-for="#Model.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.DesignedFor" class="control-label"></label>
#Html.DropDownListFor(model => model.DesignedFor,
new SelectList(ViewBag.DesignedList), new { #class = "form-control", #value = "Men" })
<span asp-validation-for="#Model.DesignedFor" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.ItemCategory" class="control-label"></label>
#Html.DropDownListFor(model => model.ItemCategory,
new SelectList(ViewBag.CategoryList), new { #class = "form-control", #value = "Clothing" })
<span asp-validation-for="#Model.ItemType" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.ItemType" class="control-label"></label>
#if (Model.DesignedFor == "Men" && Model.ItemCategory == "Clothing")
{
#Html.DropDownListFor(model => model.ItemType,
new SelectList(Enum.GetValues(typeof(RandApp.Enums.MClothing))), new { #class = "form-control" })
}
<span asp-validation-for="#Model.ItemType" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.MaterialType" class="control-label"></label>
#Html.DropDownListFor(model => model.MaterialType,
new SelectList(ViewBag.MaterialTypeList), new { #class = "form-control" })
<span asp-validation-for="#Model.MaterialType" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Color" class="control-label"></label>
#Html.DropDownListFor(model => model.Color,
new SelectList(ViewBag.ItemColorList), new { #class = "form-control" })
<span asp-validation-for="#Model.Color" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Size" class="control-label"></label>
#Html.DropDownListFor(model => model.Size,
new SelectList(ViewBag.ItemSizeList), new { #class = "form-control" })
<span asp-validation-for="#Model.Size" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Price" class="control-label"></label>
<input asp-for="#Model.Price" class="form-control" />
<span asp-validation-for="#Model.Price" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Description" class="control-label"></label>
<textarea asp-for="#Model.Description" class="form-control"></textarea>
<span asp-validation-for="#Model.Description" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" asp-for- class="btn btn-primary" />
</div>
#Html.Hidden("selectedDesignedFor", 0)
#Html.Hidden("selectedCategory", 0)
</form>
</div>
</div>
#section Scripts
{
<script>
function SetValue(input) {
var fileName = input.files[0].name;
//asp-for will generate the id and name
//so you can get the selector by using $("#ItemPhoto")
$("#ItemPhoto").val(fileName);
}
var designedFor;
$("#DesignedFor").on("change", function () {
var value = $(this).find('option:selected').val();
$(".selected-designed").removeClass(`${designedFor}`).addClass(`${value}`);
designedFor = value;
$('#selectedDesigned').val(designedFor);
});
var category;
$("#ItemCategory").on("change", function () {
var value = $(this).find('option:selected').val();
$(".selected-category").removeClass(`${category}`).addClass(`${value}`);
category = value;
$('#selectedCategory').val(category);
});
</script>
}
so i have admin page from which i upload product to db, so my goal is to get proper enum values for "Model.ItemTypes" field according to a "Model.DesignedFor" and "Model.ItemCategory" field values, for example, if "Model.DesigendFor" value is "Men" and "Model.ItemCategory" is "Clothing", "Model.ItemTypes" dropdownlist should render the enum values of MClothing.
i tried numerous of ways to solve this problem but none of them work. one way was to get DesigendFor and itemCategory values using js code and add them values as class to a "HTML.Hidden" input, but in the end, i can't use this value in a way that i want.
is there any solution to solve this problem?
I am new to mvc and I wish to access a value from the code behind just a text box value and I thought this was the logical way of doing it by passing the value as a paremeter to my action Result but when i debug firstName its showing as null?.
It is this value here that I am trying to access please excuse my ignorance I come from a long webforms background.
<input id="firstName" class="form-control" type="text" />
Also quick quesiton in relation to the controller must I always return a view that it was called from can i for example go return step2 as long as it has same layout file ? How would one tell it to go to another view other than the Save action reason I am asking is I am doing a wizard form.
My Form Markup
#using (Html.BeginForm("Step1", "Forms", FormMethod.Post, new { id = "submitForm" }))
{
#Html.AntiForgeryToken()
<h4>Health Check</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("First Name", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<input id="firstName" class="form-control" type="text" />
</div>
</div>
<div class="form-group">
#Html.Label("Middle Name", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<input id="txtmiddleName" class="form-control" type="text" />
</div>
</div>
<div class="form-group">
#Html.Label("Surname", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<input id="txtsurname" class="form-control" type="text" />
</div>
</div>
<div class="form-group">
#Html.Label("Saluation", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<input id="txtSaluation" class="form-control" type="text" />
</div>
</div>
<div class="form-group">
#Html.Label("Aliases", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<input id="txtAliases" class="form-control" type="text" />
</div>
</div>
<div class="form-group">
#Html.Label("Maritial Status", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<input id="txtmStatus" class="form-control" type="text" />
</div>
</div>
<div class="form-group">
#Html.Label("Maritial Status", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<select class="form-control"></select>
</div>
</div>
<div class="form-group">
#Html.Label("Address 2", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<input id="txtmStatus" class="form-control" type="text" />
</div>
</div>
<div class="form-group">
#Html.Label("City", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<input id="txtmStatus" class="form-control" type="text" />
</div>
</div>
<div class="form-group">
#Html.Label("Post Code", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<input id="txtmStatus" class="form-control" type="text" />
</div>
</div>
<div class="form-group">
#Html.Label("County", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<input id="txtCounty" class="form-control" type="text" />
</div>
</div>
<div class="form-group">
#Html.Label("Country", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<input id="txtmStatus" class="form-control" type="text" />
</div>
</div>
<div class="form-group">
#Html.Label("Date Of Birth", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#(Html.Kendo().DatePicker()
.Name("datepicker"))
</div>
</div>
<div class="form-group">
#Html.Label("Home Tel No", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<input id="txtmStatus" class="form-control" type="text" />
</div>
</div>
<div class="form-group">
#Html.Label("Home Work No", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<input id="txtmStatus" class="form-control" type="text" />
</div>
</div>
<div class="form-group">
#Html.Label("Fax No", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<input id="txtmStatus" class="form-control" type="text" />
</div>
</div>
<div class="form-group">
#Html.Label("Mobile No", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<input id="txtmStatus" class="form-control" type="text" />
</div>
</div>
<div class="form-group">
#Html.Label("Best Time To Call", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<select class="form-control">
<option>Morning</option>
<option>Afternoon</option>
<option>Evening</option>
</select>
</div>
</div>
<button type="submit" id="btnSave">Save</button>
}
My Controller Action Result:
public ActionResult Step1(string firstName)
{
DataAccessAdapter _adapter = new DataAccessAdapter();
TblfhcsPersonalEntity _personal = new TblfhcsPersonalEntity();
_personal.FirstName = firstName;
_adapter.SaveEntity(_personal, true);
return View();
}
For any form in HTML to submit data, all <input> tags must have a name="..." attribute. Setting id is useful for javascript, but is ignored for the form submit.
In this case, name="firstName" would be a good start because that matches with what you are binding in the Controller action method Step1.
I am relatively new to programming C# with ASP.NET MVC and I have a question. I am building some kind of cinema add show feature. I currently got the code where i can get all the CinemaShows with the right HallID based on a selected date (and send to the controller by a [Post]. Now I've put the information I need in a list of a ViewModel and I want to pass it along with the partial view so that when the POST method is called, the right info shows in a partial view. I will show the views and controllers code.
#using IVH7A5.WebUI.Models;
#using IVH7A5.Domain.Entities;
#model addShowViewModel
#{
ViewBag.Title = "addShow";
}
<div style="float:inherit">
#using (Html.BeginForm("getDateShows", "Show")) {
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class=" form-group">
<label class="control-label col-md-2">Datum</label>
<div class="col-md-10">
<input type="date" class="form-control" id="datum" name="datum" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-default">Toepassen</button>
</div>
</div>
</div>
}
</div>
<div>
#{Html.RenderPartial("_ShowsByCinema");}
</div>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Show</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label class="control-label col-md-2">Zalen</label>
<div class="col-md-10">
<select class="form-control" name="cinemanumbers" id="cinemanumbers">
#foreach (Cinema cin in Model.Cinemas) {
<option value="#cin.cinemaNumber">#cin.cinemaNumber</option>
}
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Zalen</label>
<div class="col-md-10">
<select class="form-control" name="film" id="film">
#foreach (Movie movie in Model.Movies) {
<option value="#movie.MovieTitle">#movie.MovieTitle</option>
}
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">3D</label>
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Shows.ThreeD)
#Html.ValidationMessageFor(model => model.Shows.ThreeD, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Starttijd</label>
<div class="col-md-10">
#Html.EditorFor(model => model.Shows.StartTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Shows.StartTime, "", 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>
}
Note I do have some Dutch labels, as seen I use a different ViewModel that I want to pass to the partial view. My guess is that the RenderPartial() line needs some work.
My partial view:
#using IVH7A5.WebUI.Models;
#using IVH7A5.Domain.Entities
#model List<ShowsByCinema>
<div class="row">
<div class="col-lg-6 col-lg-offset-3 col-md-8 col-md-offset-2 col-sm-12 movie-film-times">
<h3>Zalen en tijden:</h3>
<div class="movie-by-day">
#foreach (ShowsByCinema x in Model) {
<div class="row">
<div class="col-xs-3 movie-day">
<strong>#x.cinemaNumber</strong>
</div>
<div class="col-xs-9">
#foreach (Show s in x.Shows) {
#s.StartTime.ToString("HH:mm") #:- #s.StartTime.AddMinutes(s.movie.MovieLength)
}
</div>
</div>
}
</div>
</div>
</div>
And, of course, the controller:
using IVH7A5.Domain.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IVH7A5.Domain.Entities;
using IVH7A5.WebUI.Models;
namespace IVH7A5.WebUI.Controllers {
public class ShowController : Controller {
private ICinemaRepository cinemaRepository;
private IMovieRepository movieRepository;
private IShowRepository showRepository;
public ShowController(ICinemaRepository cinemaRepo, IMovieRepository movieRepo, IShowRepository showRepo) {
cinemaRepository = cinemaRepo;
showRepository = showRepo;
movieRepository = movieRepo;
}
// GET: Show
public ActionResult Index() {
var model = new addShowViewModel();
model.Cinemas = cinemaRepository.cinemas;
model.Movies = movieRepository.Movies;
return View("addShow", model);
}
[HttpPost]
public ActionResult getDateShows(FormCollection form) {
List<ShowsByCinema> ShowsByCinemaList = new List<ShowsByCinema>();
DateTime date = Convert.ToDateTime(form["datum"]);
foreach (Cinema c in cinemaRepository.cinemas) {
ShowsByCinemaList.Add(new ShowsByCinema {
cinemaNumber = c.cinemaNumber,
Shows = showRepository.getshowsByCinemaAndDate(date, c.cinemaID)
});
}
return PartialView("_ShowsByDayPartial", ShowsByCinemaList);
}
}
}
So, to give a quick summary: I would like to know to render the partial view with the proper ViewModel when I call the POST method getDateShows. I am very new to programming in general and I would like to apologize if it contains code that is in contradiction with the code conventions. I hope someone can give me the solution to my problem. If any more information/code is required, feel free to ask.
I have this problem with a viewmodel, when the view is posted I'm getting null values for all the properties.
I've researched a bit, I can see multiple ppl have this problem, I tried some of the solutions but none of them works for me.
This is what I have:
Viewmodel:
public class EventViewModel
{
public projectEvent ProjectEvent { get; set; }
public List<eventType> eventTypes { get; set; }
}
Controller:
[HttpGet]
public ActionResult AddEditEvent(int? id)
{
var eventViewModel = new EventViewModel();
var projectEventModel = new projectEvent();
if (id != null)
{
using (var db = new DBEntities())
{
projectEventModel = (from p in db.projectEvents
where p.eventID == id
select p).FirstOrDefault();
}
}
eventViewModel.ProjectEvent = projectEventModel;
using (var db = new DBEntities())
{
eventViewModel.eventTypes = (from p in db.eventTypes
select p).ToList();
}
return View(eventViewModel);
}
[HttpPost]
public ActionResult AddEditEvent(EventViewModel projectEvent)
{
if (ModelState.IsValid)
{
using (var db = new DBEntities())
{
db.projectEvents.AddOrUpdate(projectEvent);
db.SaveChanges();
}
}
return RedirectToAction("Events");
}
View:
#model TTB.ViewModels.EventViewModel
#{
Layout = "~/Views/Shared/_Layout_Main.cshtml";
}
<h2>Add/Edit Event</h2>
#using (Html.BeginForm("AddEditEvent", "Admin"))
{
<div class="container">
<div class="col-md-8">
<div class="form-group">
<label for="name">Name</label>
#Html.TextBoxFor(m => m.ProjectEvent.eventName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.ProjectEvent.eventName)
</div>
<div class="form-group">
<label for="name">Date</label>
#Html.TextBoxFor(m => m.ProjectEvent.eventDate, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.ProjectEvent.eventDate)
</div>
<div class="form-group">
<label for="name">Event Type</label>
#Html.DropDownListFor(v => v.ProjectEvent.eventType, new SelectList(Model.eventTypes, "eventTypeID", "eventTypeName"), new { #class = "form-control dropdown" })
</div>
#Html.HiddenFor(m => m.ProjectEvent.eventID)
</div>
<div class="col-md-8">
<input type="submit" class="btn btn-success btn-lg btnSaveEdit" value="Save" />
</div>
</div>
}
What am I doing wrong?
Update
Rendered html output:
<form action="/Admin/AddEditEvent" method="post"> <div class="container">
<div class="col-md-8">
<div class="form-group">
<label for="name">Name</label>
<input class="form-control" data-val="true" data-val-required="The eventName field is required." id="ProjectEvent_eventName" name="ProjectEvent.eventName" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="ProjectEvent.eventName" data-valmsg-replace="true"></span>
</div>
<div class="form-group">
<label for="name">Date</label>
<input class="form-control" data-val="true" data-val-date="The field eventDate must be a date." data-val-required="The eventDate field is required." id="ProjectEvent_eventDate" name="ProjectEvent.eventDate" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="ProjectEvent.eventDate" data-valmsg-replace="true"></span>
</div>
<div class="form-group">
<label for="name">Event Type</label>
<select class="form-control dropdown" id="ProjectEvent_eventType" name="ProjectEvent.eventType"><option value="1">movie</option>
</select>
</div>
<input data-val="true" data-val-number="The field eventID must be a number." data-val-required="The eventID field is required." id="ProjectEvent_eventID" name="ProjectEvent.eventID" type="hidden" value="0" />
</div>
<div class="col-md-8">
<input type="submit" class="btn btn-success btn-lg btnSaveEdit" value="Save" />
</div>
</div>
</form>
It is because you have a property on your model called projectEvent and you refer to your model as projectEvent when it is passed back into the controller.
Change
public ActionResult AddEditEvent(EventViewModel projectEvent)
To
public ActionResult AddEditEvent(EventViewModel model)
(or another name of your choosing)
http://tech.pro/blog/1930/don-t-name-a-model-the-same-as-a-property-you-re-trying-bind-in-aspnet-mvc
I have this model, Customer . When i get the information with an id, it works just fine.
Like ;
/Customer/Entity/5
#model ProgSpace.Models.Customer
#{
ViewBag.Title = Model.Name;
Layout = "~/Views/Shared/_MainLayout.cshtml";
}
#section bodypane
{
#using (Html.BeginForm("Entity", "Customer", FormMethod.Post, new { #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="col-md-12">
<div class="col-md-1">
<label>Customer No:</label>
<h4># #(Model.ID) </h4>
</div>
<div class="clearfix"></div><br />
<div class="col-md-2">
<div class="col-md-12">
<div class="col-md-12 fileupload fileupload-exists" data-provides="fileupload">
<div class="fileupload-preview fileupload-exists thumbnail" style="width: 200px; height: 150px;">
<img src="#Model.Picture.Path" />
</div>
<div>
<span class="btn btn-default btn-file">
<span class="fileupload-new">Add Pic </span>
<span class="fileupload-exists">Change</span><input name="file" id="file" type="file">
</span>
Remove
</div>
</div>
</div>
</div>
<div class="col-md-10">
<div class="col-md-3">
<label>Name *</label>
#Html.TextBoxFor(model => model.Name, new { #class = "form-control"})
</div>
<div class="col-md-3">
<label>Company</label>
#Html.TextBoxFor(model => model.Contact.Company, new { #class = "form-control"})
</div>
<div class="col-md-3">
<label>Phone </label>
#Html.TextBoxFor(model => model.Contact.Phone, new { #class = "form-control" })
</div>
</div>
<div class="clearfix"><br /></div>
<p> </p>
<div class="col-md-12">
<div class="btn-group">
<button class="btn btn-danger btn-lg">Cancel</button>
<button type="submit" class="btn btn-success btn-lg">Send</button>
</div>
</div>
</div>
}
}
And in the controller i have these actions.
public ActionResult Entity(int id)
{
Customer cust= sis.Customers.Where(t => t.ID == id).FirstOrDefault();
return View(cust);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Entity(Customer cust, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
/* Do something */
}
else
{
}
return View(cust);
}
When the verb is GET , it's fine. But when i post this form and when the second action (HttpPost action) kicks in , view throws an error..
Object reference not set to an instance of an object
which marks the Model.ID is null in the view.
<div class="col-md-1">
<label>Customer No:</label>
<h4># #(Model.ID) </h4> ---> THIS HERE THROWS NULL EXCEPTION
</div>
I've tried to add a HiddenFor for the Model.ID like
#Html.HiddenFor(t => t.ID)
but it didn't change anything.
How do i get back to the same view with the same context again ?