как обращаться с одним из многих отношений.обрабатывать отношения для многих при обновлении db
Модели:
public partial class Student
{
public student()
{
this.Courses = new HashSet<Course>();
}
public int pkID { get; set; }
public string Name { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public partial class Course
{
public int pkID { get; set; }
public Nullable<int> fkStudentID { get; set; }
public string Name { get; set; }
public virtual Student Student { get; set; }
}
Контроллер:
public ActionResult Create([Bind(Include = "pkID,Name")] Student student)
{
student.Courses.Add(course); // How to fetch course from the Student/Create.cshtml and convert it to type Course
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
Вид:
// Student/Create.cshtml
@model School.Student
@{
ViewBag.Title = "Create";
}
<div>
@Html.ActionLink("Tillbaka till lista", "Index")
</div>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, "Namn", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Name", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Courses, "Kurs", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Courses", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Courses, "", new { @class = "text-danger" })
</div>
</div>
}
Рассматриваются вопросы, как извлечь данные курсы из .cshtml и обновления БД. В функции create я получаю только что полученное имя, я знаю, что можно использовать Request [«Курсы»], но как его сохранить в таблице курсов?
Спасибо!
Вопрос не ясен, можете ли вы подробно рассказать, что вы ищете? – Ravi
Ravi Я хочу добавить курсы для ученика, когда пользователь добавляет курс, я не знаю, как получить выбранное значение из .cshtml для моей функции post/create? –
, так что у вас есть один выбор или множественный выбор Coure? – Ravi