Reputation: 1842
I'm trying to make a custom create form using an Editor Template and Entity Framework. The problem I'm having is that all of my fields show up with no value attribute set. This throws an error in the ModelState when dealing with the hidden key value because it essentially has no value. Here's an example of what I'm doing.
Car.cs
public class Car
{
[Key]
[HiddenInput(DisplayValue = false)]
public int CarID{ get; set; }
[required]
public string Make { get; set; }
[required]
public string ModelName { get; set; }
[required]
public int Year { get; set; }
}
Car.cshtml (Editor Template)
@model Car
@Html.HiddenFor(c => c.CarID, new { Value = "0" })
@Html.EditorFor(c => c.Make)
@Html.EditorFor(c => c.ModelName)
@Html.EditorFor(c => c.Year)
CreateCar.cshtml (View)
@model Car
<form id="create-car-form" method="post">
@Html.EditorForModel()
<a onclick="SubmitForm()">Submit</a>
</form>
Now this is only an example. I'm actually submitting my form through an ajax call to avoid reloading the page and I'm setting up dropdowns for Make and ModelName in my editor template. However I'm able to get all the information ok in my controller action as long as it's been entered in the form.
If a field is left blank then the ModelState gets an error because a value was empty when it expected some value. This is particularly a problem with hidden fields as it cannot receive a value from the user, Nor do I want it to.
Further exploration shows that the Html generated for the fields all have an empty 'value' attribute. And by that I mean that the input tag looks something like this in the inspector:
<input data-val="true" data-val-required="The CarID field is required." id="CarID" name="CarID" type="hidden" value>
However copying the element from the inspector and pasting it gives this:
<input data-val="true" data-val-required="The CarID field is required." id="CarID" name="CarID" type="hidden" value="">
This is obviously my culprit but I can't understand why the value attribute is not getting set when I specify it in the editor template.
EDIT CarsView.cshtml
<div>
@Html.Partial("CreateCar", new Car());
</div>
JavaScript
function SubmitForm() {
var form = $('#create-car-form');
$.ajax({
type: "POST",
url: "Home/CreateCar",
data: form.serialize(),
dataType: 'html',
success: function (data) {
console.log(form.serialize();
}
});
}
The console log will reveal that form.serialize()
returns the following string:
"CarID=&ModelName=Camry&Make=Toyota&Year=2010"
This shows that there is no value for CarID. This is also the only JS that I've used thus far for the application and it occurs after the form has already been setup which is why I believe something strange is happening with the Html helpers.
Upvotes: 1
Views: 1639