View:
@model My.Data.Section
@using (Html.BeginForm("Save", "Sections"))
{
@Html.Partial("_Fields", Model.Fields);
<input type="submit" value="Save">
}
View JS:
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
// do some stuff with the returned partial
}
});
}
return false;
});
});
</script>
Model:
Comes from my data layer (EF5/DBContext/unitofwork)
namespace My.Data
{
using System;
using System.Collections.Generic;
public partial class Section
{
public Section()
{
this.Fields = new HashSet<Field>();
}
public int SectionID { get; set; }
public int FormID { get; set; }
public string Name { get; set; }
public Nullable<int> PrevSection { get; set; }
public Nullable<int> NextSection { get; set; }
public int SortOrder { get; set; }
public virtual ICollection<Field> Fields { get; set; }
public virtual Form Form { get; set; }
}
}
Controller:
[HttpPost]
public ActionResult Save(Section model, FormCollection fc)
{
// do some fun stuff
return PartialView("_Section", model);
}
When I debug the controller, the model object is not deserialized, I assume this is because I am not using labelfor & textboxfor ect ?
When I inspect the FormCollection object, this has all the keys I need and all the values, however, I’d like to get some other values from my fields, like data-fieldid-itemid=”1″, how would I accomplish this? What’s the best way to do this?
Is it required that I use LabelFor/TextboxFor ?
I guess what I was expecting was the model object to come through with the data filled in, and the sub items of my model object, particularly public virtual ICollection Fields { get; set; } to also be filled in.
I have a feeling I’m missing some concept here, any ideas?
Thanks!
First, you shouldn’t use Partial views for forms. Instead, you should use EditorTemplates.
Second, you can’t get attributes because these are not posted to the server by the browser. MVC is stuck with the mechanisms that the browser supports.
Your options would be, using a submit handler to populate hidden fields with your attributes, put the data in hidden fields to begin with, do an ajax post in which you set all the data you want to post, or simply have your controller “remember” the attributes it set in the GET.