.NET 4.5
ASPNET.MVC 5
On the web page of interest, within a list of complex objects, I am trying to edit only one property for each complex object.
Let's say that my complex class looks like this:
public class MyClass
{
[Required]
public int MyClassID {get; set;} // Primary Key
[Required]
public int Prop1 { get; set; } // an integer property
[Required]
public string Prop2 { get; set; } // a string property
[Required]
public EnumType Prop3 { get; set; } // an enum property that's being changed
}
In my form, I am trying to edit a list of MyClass
objects in which only Prop3
is changed.
These are my Get and Post methods in my Controller:
[HttpGet]
public ActionResult ChangeJustProp3InList()
{
.
. /* some validation stuff */
.
var myList = new List<MyClass>
{
/*... some MyClass objects ...*/
};
return View(myList);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChangeJustProp3InList(List<MyClass> myList)
{
.
. /* some stuff I think is unnecessary for this question */
.
}
This is my View:
@model IList<MyClass>
.
. /* some html */
.
@using (Html.BeginForm("ChangeJustProp3InList", "MyController", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
for (int i = 0; i < Model.Count; i++)
{
Html.HiddenFor(model => Model[i].MyClassID);
Html.HiddenFor(model => Model[i].Prop1);
Html.HiddenFor(model => Model[i].Prop2);
var uniqueID = "MyClass" + Model[i].MyClassID; <!-- html needs unique "id" attribute for each MyClass object -->
Html.RadioButtonFor(model => Model[i].Prop3, EnumType.Choice1, new { id = uniqueID });
Html.RadioButtonFor(model => Model[i].Prop3, EnumType.Choice2, new { id = uniqueID });
Html.RadioButtonFor(model => Model[i].Prop3, EnumType.Choice3, new { id = uniqueID });
}
<a><input type="submit" value="Submit" class="btn btn-default center-block" /></a>
}
(There may be some syntax errors above relating to going between c# and html markup with razor. Please ignore those, as I tried to eliminate as much unnecessary code as possible.)
Note that I am the Prop3
property is an enum being updated with a radio button control.
So, presently, I am able to post any changes to the Prop3
property for each MyClass object. However, every other property (Prop1, Prop2, and even MyClassID) is reset to default values (null, 0, etc.). I would like retain the values that were there originally.
I was thinking of Binding using the BindAttribute as follows...
public ActionResult ChangeJustProp3InList([Bind(Include = "<only Prop3>"] List<MyClass> myList)
But I couldn't find anything that binds a single property within a list of complex types. Any ideas?
My question is somewhat related to the one posed here: ASP.Net MVC - How to include / exclude binding of certain child collection / enumerable properties?