viewmodel returns null on postback mvc 5 - c#

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

Related

Editing an item inline in the Index-view throws off model binding. How to make it work?

I am trying to make a system where the user can click on an item in a list, and then edit that item while still remaining in the Index-view.
My attempt is just a mix between Index.cshtml and Edit.cshtml:
#model IEnumerable<MyStore.Models.ProductIdentifier>
#{int primary_id = (this.ViewContext.RouteData.Values["primary_id"] != null
? int.Parse(this.ViewContext.RouteData.Values["primary_id"].ToString())
: 0);
}
#foreach (var item in Model)
{
if (item.Id == primary_id)
{
// This list-item is editable (copied from Edit.cshtml):
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="#item.Id" />
<div class="form-group col-lg-4">
<input asp-for="#item.Label" class="form-control" />
<span asp-validation-for="#item.Label" class="text-danger"></span>
</div>
<div class="form-group col-lg-6">
<input asp-for="#item.Description" class="form-control" />
<span asp-validation-for="#item.Description" class="text-danger"></span>
</div>
<div class="form-group col-lg-1">
<input asp-for="#item.SortOrder" class="form-control" />
<span asp-validation-for="#item.SortOrder" class="text-danger"></span>
</div>
<div class="form-group col-lg-1">
<button type="submit" value="Save" class="btn btn-primary">
<span class="glyphicon glyphicon-floppy-disk"></span> Save
</button>
</div>
</form>
}
else
{
// This list-item is just a plain list-item:
<div class="row table">
<div class="col-lg-4">
<a asp-action="Index" asp-route-primary_id="#item.Id">
#Html.DisplayFor(modelItem => item.Label)
</a>
</div>
<div class="col-lg-6">
#Html.DisplayFor(modelItem => item.Description)
</div>
<div class="col-lg-1">
#Html.DisplayFor(modelItem => item.SortOrder)
</div>
<div class="col-lg-1">
<a asp-action="Delete" asp-route-id="#item.Id" class="btn btn-xs btn-danger">
<span class="glyphicon glyphicon-trash"></span>
</a>
</div>
</div>
}
}
The form data is supposed to be posted to the Edit-method in the controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Label,Description,SortOrder")] ProductIdentifier productIdentifier)
{
if (id != productIdentifier.Id) { return NotFound(); }
if (ModelState.IsValid)
{
try
{
_context.Update(productIdentifier);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductIdentifierExists(productIdentifier.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(productIdentifier);
}
... but because I had to add #item. in front of the elements in the form (because the model is an IEnumerable, and I only want to post a single object), the model binding no longer works, and a null object is being posted.
How can I get it to work?
I made it work!
First, I created a ViewModel which contains both an ICollection of identifiers and a single instance of an identifier:
public class ViewModelEditIdentifierInIndexView
{
public ViewModelProductIdentifier SingleItem { get; set; }
public ICollection<ViewModelProductIdentifier> ListOfItems { get; set; }
}
I had to make some changes in the Index method in the controller, to cater for the viewmodel:
public async Task<IActionResult> Index(int? primary_id)
{
ProductIdentifier pi = await _context.ProductIdentifiers
.Where(i => i.Id == primary_id)
.SingleOrDefaultAsync();
ViewModelEditIdentifierInIndexView ViewModel = new ViewModelEditIdentifierInIndexView
{
SingleItem = _mapper.Map<ViewModelProductIdentifier>(pi),
ListOfItems = _mapper.Map<ICollection<ViewModelProductIdentifier>>(await _context.ProductIdentifiers.ToListAsync())
};
return View(ViewModel);
}
Then, I changed the model in the Index-view:
#model MyStore.Models.ViewModels.ViewModelEditIdentifierInIndexView
Then, I changed the edit form. The most important change is the addition of name-tags on each input-field:
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="SingleItem.Id" name="Id" />
<div class="form-group col-lg-4" style="padding-left:0px;">
<input asp-for="SingleItem.Label" name="Label" class="form-control" />
<span asp-validation-for="SingleItem.Label" class="text-danger"></span>
</div>
<div class="form-group col-lg-6" style="padding-left:0px;">
<input asp-for="SingleItem.Description" name="Description" class="form-control" />
<span asp-validation-for="SingleItem.Description" class="text-danger"></span>
</div>
<div class="form-group col-lg-1" style="padding-left:0px;">
<input asp-for="SingleItem.SortOrder" name="SortOrder" class="form-control" />
<span asp-validation-for="SingleItem.SortOrder" class="text-danger"></span>
</div>
<div class="form-group col-lg-1" style="padding-left:0px;">
<button type="submit" value="Save" class="btn btn-xs btn-success">
<span class="glyphicon glyphicon-floppy-disk"></span>
</button>
<a href="/Admin/ProductIdentifiers" class="btn btn-xs btn-warning">
<span class="glyphicon glyphicon-chevron-left"></span>
</a>
</div>
</form>
I didn't have to make any changes to the Edit method in the controller.

MVC5 model not recory the text value of textbox

I don't know what I'm doing bad.
Controller:
public class PictureController : Controller
{
// GET: Picture
public ActionResult Index()
{
return View();
}
public ActionResult AddGroup()
{
ModelPhotoGroup p = new ModelPhotoGroup();
return View(p);
}
[HttpPost]
public ActionResult AddGroup(ModelPhotoGroup p)
{
return View(p);
}
}
In AddGroup of HttpPost I get a p.GroupName = null but I'm writing text in the textbox
View:
#model Boda.WebUI.Models.ModelPhotoGroup
#{
ViewBag.Title = "";
}
<h2>Crear grupo de fotos</h2>
<div class="row">
<div class="col-lg-6 col-lg-offset-3 col-md-6 col-md-offset-3 col-sm-8 col-md-offset-2">
<div class="well">
#using (Html.BeginForm())
{
#Html.HiddenFor(x => x.GroupName)
<div class="form-group">
#Html.LabelFor(x => x.GroupName)
#Html.TextBoxFor(x => x.GroupName, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.GroupName)
</div>
<div class="btn-group">
<input type="submit" value="Guardar" class="btn btn-success" />
#Html.ActionLink("Cancelar y volver a la lista de Fotografias", "Index", null, new
{
#class = "btn btn-default"
})
</div>
}
</div>
</div>
</div>
This is the view. Only I have one TextBoxt to write the name of group
HTML Generated:
<form action="/Picture/AddGroup" method="post"><input id="GroupName" name="GroupName" type="hidden" value=""> <div class="form-group">
<label for="GroupName">GroupName</label>
<input class="form-control" id="GroupName" name="GroupName" type="text" value="">
<span class="field-validation-valid" data-valmsg-for="GroupName" data-valmsg-replace="true"></span>
</div>
<div class="btn-group">
<input type="submit" value="Guardar" class="btn btn-success">
<a class="btn btn-default" href="/Picture">Cancelar y volver a la lista de Fotografias</a>
</div>
You have included
#Html.HiddenFor(x => x.GroupName)
before
#Html.TextBoxFor(x => x.GroupName)
The value of the hidden input will be whatever the default value of GroupName was when you initialized the model (i.e. null)
When you POST, the DefaultModelBinder sets the value of property GroupName to the first value it reads from the form data (that of the hidden input) and ignores any subsequent values with the same name, so the property is always null.
Remove the hidden input and your model will be correctly bound with the value in the textbox.
It's because you did not specify the action and controller,
add the name of action and controller in your form
#using(Html.BeginForm("AddGroup","Picture"))

POST action passing null ViewModel

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);
}

Ajax query refreshing whole page instead of part

I have simple View where I have a ajax form I use for filtering records:
#using (Ajax.BeginForm("Index", new AjaxOptions()
{
InsertionMode=InsertionMode.Replace,
UpdateTargetId="dane"
}))
{
#Html.Partial("SearchTab")
}
#Html.Partial("ShowPartial") // <--- id="dane"
Partial SearchTab:
<div class="row">
<div class="col-lg-3">
<div class="input-group">
<div class="input-group-addon name">
User name:
</div>
<input type="text" name="name" class="form-control" />
</div>
</div>
<div class="col-lg-3">
<div class="input-group">
<div class="input-group-addon surname">
User surname:
</div>
<input type="text" name="surname" class="form-control" />
</div>
</div>
<div class="col-lg-3">
<div class="input-group">
<div class="input-group-addon devicename">
Device name:
</div>
<input type="text" name="deviceName" class="form-control" />
</div>
</div>
<div class="col-lg-3">
<div class="input-group">
<div class="input-group-addon devicemanufacturer">
Device Manufactuer:
</div>
<input type="text" name="deviceManufacturer" class="form-control" />
</div>
</div>
</div>
<input type="submit" class="btn btn-default" value="Filter" id="filter"/>
<br />
Controller action:
public ActionResult Index(string name, string surname ,string deviceName, string deviceManufacturer, string Page)
{
bool RoleId = ad.CheckIfAdmin(Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.LastIndexOf(#"\") + 1));
ViewBag.RoleId = RoleId;
var deviceusages = db.DeviceUsages.Include(d => d.DeviceInstance).Include(d => d.Storage).Include(d => d.User).Where(w=>w.UserId!=6).Skip((int.Parse(Page)-1)*30).Take(30);
if(name!="" && name!=null)
{
deviceusages = deviceusages.Where(w => w.User.Name.Contains(name));
}
if (surname != "" && surname != null)
{
deviceusages = deviceusages.Where(w => w.User.Surname.Contains(surname));
}
if (deviceName != "" && deviceName != null)
{
deviceusages = deviceusages.Where(w => w.DeviceInstance.Device.Name.Contains(deviceName));
}
if (deviceManufacturer!= "" && deviceManufacturer != null)
{
deviceusages = deviceusages.Where(w => w.DeviceInstance.Device.Manufacturer.Contains(deviceManufacturer));
}
return View(deviceusages.ToList());
}
After writing something into input field and pressing filter. Ajax should refresh ShowPartial and keep values in the input fields from SerchTab but instead I get filtered records and inputs are getting empty. Can anyone suggest me edits to change this behaviour
If you are intending to
return View()
you should also return the original model so that control values can be populated with your captured values.
Alternatively if you just need to return the list:
deviceusages.ToList()
Then you can return a PartialView() e.g.;
return PartialView(deviceusages.ToList());
Ok I found cause of a problem.
I need to change this code
<div class="input-group">
<div class="input-group-addon name">
User name:
</div>
<input type="text" name="name" class="form-control" />
</div>
into same thing made wit use of .net Html helpers.
After this change everything works!
#Html.Label("User name: ", new { #class = "input-group-addon" })
#Html.TextBox("name", null, new { #type = "text", #class = "form-control" })

The parameter conversion from type 'System.String' to type ''Y' failed because no type converter can convert between these types

I'm stucked with this error, I checked values are not null. This error came out when I tried to hit on the Save button.
Please help me, this is the error:
The parameter conversion from type 'System.String' to type 'ULIV.ViewModels.NewProposal' failed because no type converter can convert between these types.
ModelState.IsValid is false.
Here's the View Model used:
public class PurchaseOrderViewModel
{
[Key]
public int ID { get; set; }
public IEnumerable<Institution> Institution { get; set; }
[Required]
public string PurchaseOrderNo { get; set; }
[Required]
public DateTime PurchaseOrderDate { get; set; }
[Required]
public DateTime ReceivedDate { get; set; }
public string Remarks { get; set; }
public IEnumerable<NewProposal> Proposal { get; set; }
public IEnumerable<PODetail> PODetail { get; set; }
public IEnumerable<NewProposal> AddedProposal { get; set; }
}
This is the Controller Action:
[HttpPost]
public ActionResult Create(PurchaseOrderViewModel purchaseorderviewmodel)
{
purchaseorderviewmodel.AddedProposal = (List<ULIV.ViewModels.NewProposal>)Session["AddedProposal"];
//purchaseorderviewmodel.Proposal = db.NewProposal.Where(x => x.Status.StatusID == 3).ToList();
int instituionId = Convert.ToInt32(Session["InstitutionID"]);
purchaseorderviewmodel.Institution = db.Institutions.Where(x => x.InstitutionID == instituionId).ToList();
if (ModelState.IsValid)
{
db.PurchaseOrderViewModels.Add(purchaseorderviewmodel);
db.SaveChanges();
return RedirectToAction("Index","Fulfillment");
}
ViewBag.Proposal = new SelectList(db.NewProposal.Where(x => x.Status.StatusID == 3), "ProposalID", "ProposalCode");
return View(purchaseorderviewmodel);
}
Also, these are the values on the immediate window:
((List<ULIV.ViewModels.NewProposal>)Session["AddedProposal"]).FirstOrDefault()
DateModified: {1/15/2014 2:57:52 PM}
FinalUnitPrice: 23
FinalVolume: 34
getdatestring: "1/15/2014"
Institution: {System.Data.Entity.DynamicProxies.Institution_B01649AB79941CE0188D081B425698F4FD6629E82FDB13CCE17B03E348459273}
InstitutionID: 1
Product: {ULIV.Models.ProductModel}
ProductID: 1
ProposalCode: "PC-2014-00001"
ProposalID: 1
ProposedUnitPrice: 3
ProposedVolume: "2"
RelatedProposalCode: ""
Remarks: "hello"
Status: {ULIV.Models.Status}
StatusID: 3
VaccineType: {ULIV.Models.VaccineType}
VaccineTypeID: 1
((List<ULIV.ViewModels.NewProposal>)Session["AddedProposal"]).FirstOrDefault()
This is the VIEW:
<div class="row">
#using (Html.BeginForm("Create", "PurchaseOrder",
new { ReturnUrl = ViewBag.ReturnUrl },
FormMethod.Post, new { #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<h1 class="subpage-headline font-global">New Purchase Order</h1>
<div class="row">
<h2 class="subpage-headline2 font-global">New Purchase Order</h2>
#*<form class="form-horizontal" role="form">*#
#foreach (var inst in Model.Institution)
{
<div class="row-div">
<div class="form-group">
<label class="col-sm-2 control-label">Institution Name:</label>
<div class="col-sm-3">
<label class="control-text-label">#Html.DisplayFor(modelItem => inst.InstitutionName)</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Account Classifications:</label>
<div class="col-sm-3">
<label class="control-text-label">Private</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Employee Population:</label>
<div class="col-sm-3">
<label class="control-text-label">50</label>
</div>
</div>
</div>
<div class="row-div">
<div class="form-group">
<label class="col-sm-2 control-label">Address:</label>
<div class="col-sm-4">
<label class="control-text-label">Ninoy Aquino Ave. Clark Pampanga Clark Freeport Zone 1500</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Telephone No.:</label>
<div class="col-sm-3">
<label class="control-text-label">599-3146</label>
</div>
</div>
</div>
}
#*</form>*#
#*<form class="form-horizontal" role="form">*#
<div class="form-group">
<label class="col-sm-2 control-label">Purchase Order Number:</label>
<div class="col-sm-4">
#Html.TextBoxFor(model => model.PurchaseOrderNo, new { #class = "form-control", #type = "text" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Purchse Order Date:</label>
<div class="col-sm-4">
#Html.TextBoxFor(model => model.PurchaseOrderDate, new { #class = "form-control datepicker", #type = "text" })
</div>
</div>
<div class="row">
<label class="col-sm-2"></label>
<label class="col-sm-2 font-md">Proposal Code <span class="required">*</span></label>
<label class="col-sm-2 font-md">Description <span class="required">*</span></label>
<label class="col-sm-2 font-md">Unit Price w/ VAT <span class="required">*</span></label>
<label class="col-sm-1 font-md">Total Units <span class="required">*</span></label>
<label class="col-sm-2 font-md">Total Amount w/ VAT <span class="required">*</span></label>
<label class="col-sm-1"></label>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Proposal:</label>
<div class="col-sm-2">
#Html.DropDownList("ProposalID", new SelectList(ViewBag.Proposal, "Value", "Text"), "SELECT Proposal", new { #class = "form-control input", #type = "text", #name = "ddlInst" })
</div>
<div class="col-sm-2">
<input type="text" class="form-control" id="prodDesc_0">
</div>
<div class="col-sm-2">
<input type="text" class="form-control" id="unitPrice_0">
</div>
<div class="col-sm-1">
<input type="text" class="form-control" id="totalUnits_0">
</div>
<div class="col-sm-2">
<input type="text" class="form-control" id="totalAmount_0">
</div>
<div class="col-sm-1">
<button type="button" class="btn btn-primary" onclick="AddProposal()">Add</button>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Product:</label>
<div class="col-sm-9">
<table class="table table-bordered table-hover">
<thead>
<tr class="th-center">
<th>Proposal Code</th>
<th>Description</th>
<th>Unit Price VAT</th>
<th>Total Units</th>
<th>Total Amount w/ VAT</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#Html.HiddenFor(model => model.AddedProposal)
#if (Model.AddedProposal != null)
{
foreach (var prop in Model.AddedProposal)
{
<tr class="text-center">
<td>#Html.DisplayFor(modelItem => prop.ProposalCode)</td>
<td>#Html.DisplayFor(modelItem => prop.Product.Description)</td>
<td>#Html.DisplayFor(modelItem => prop.FinalUnitPrice)</td>
<td>#Html.DisplayFor(modelItem => prop.FinalVolume)</td>
<td>3875.75</td>
<td class="text-center">
<a href="#">
<img src="../../Images/icon_delete.png" width="16" height="16"></a>
</td>
</tr>
}
}
#if (Model.AddedProposal == null)
{
}
</tbody>
</table>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Received Date:</label>
<div class="col-sm-4">
#Html.TextBoxFor(model => model.ReceivedDate, new { #class = "form-control datepicker", #type = "text" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Remarks:</label>
<div class="col-sm-4">
#Html.TextBoxFor(model => model.Remarks, new { #class = "form-control", #type = "text" })
</div>
</div>
#*</form>*#
</div>
<div class="row col-xs-offset-2" style="padding-top: 30px;">
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-primary" onclick="window.location='#Url.Action("Index", "Fulfillment")'">Cancel</button>
</div>
}
Please help this is the first time I encounter this kind of error. I'm not sure if the error comes from the ""
GOT IT!
I just removed this line of code:
#Html.HiddenFor(model => model.AddedProposal)
I just found a very ornery cause for this error.
public async Task<ActionResult> Add(string m = null) { }
[HttpPost]
public async Task<ActionResult> Add(FooViewModel m) { }
In the Get method I have an optional string m = null argument, meanwhile, the Post method of course has the model passed in. Well, because in this case I named that variable m as well, that's what caused this error. Ugly and maybe a bug?
For me, it was referencing a type rather than a field. What I had was:
Html.DropDownListFor(m => m.SiteExtendedAttributeValues[0] etc.
I changed it to:
Html.DropDownListFor(m => m.SiteExtendedAttributeValues[0].SiteExtendedAttributeDefinitionId
Error went away.
there's probably string value in Session["AddedProposal"], so when you try to explicitly convert it to a NewProposal you get an error

Categories