Reputation: 51
I have a view with the name "Create". This view gets the "SchoolViewModel" which contains two classes:
public class SchoolViewModel
{
public List<Teacher> ListTeacher { get; set; }
public List<SchoolClass> ListSchoolClass { get; set; }
public ClassComplete ClassComplete { get; set; }
}
Each list in "SchoolViewModel" provides data from a database.
At the "Create" page you should be able now to select a teacher and class (DropDownList). The "ClassComplete" object contains the two classes (Teacher and SchoolClass) and the roomname
public class ClassComplete
{
public string RoomName { get; set; }
public SchoolClass SchoolClass { get; set; }
public Teacher Teacher { get; set; }
}
I want only to post the "ClassComplete" object.
My ActionResult
[HttpPost]
public ActionResult Create(ClassComplete cp)
{
// Do something
return View();
}
Edit: Razor View
@using (Html.BeginForm())
{
@Html.EditorFor(m => m.ListTeacher[0].TeacherName)
@Html.EditorFor(m => m.ListSchoolClass[0].ClassName)
@Html.TextBoxFor(m => m.cl.RoomName)<br />
<input type="submit" value="Click" />
}
Is this the right way ?
best regards
Upvotes: 1
Views: 65
Reputation: 1039408
If you want to POST only ClassComplete
model you will need to indicate the binding prefix:
[HttpPost]
public ActionResult Create([Bind(Prefix="ClassComplete")] ClassComplete cp)
{
// Do something
return View();
}
and in your view:
@using (Html.BeginForm())
{
@Html.TextBoxFor(m => m.ClassComplete.RoomName)
<br />
<input type="submit" value="Click" />
}
The TextBoxFor
will generate the following input field in the resulting markup:
<input type="text" name="ClassComplete.RoomName" />
Notice the name
of the input field. That's the reason why you need to indicate this prefix in your controller action.
This will also work for the other properties if you want to send them you just need to include the corresponding input fields:
@Html.TextBoxFor(m => m.ClassComplete.SchoolClass.SomeProperty)
@Html.TextBoxFor(m => m.ClassComplete.Teacher.SomeOtherProperty)
...
Upvotes: 2