В вашем случае вы должны использовать строку запроса <a href="/add-trainee?sessionid=123">Add trainee</a>
Добавить стажера
, в то время как / add-trainee route к вашему методу TraineeController AddTrainee
Я добавляю пример кода
namespace WebApplication1.Controllers
{
public class Session
{
public int SessionId { get; set; }
public string Name { get; set; }
public List<Trainee> Trainees { get; set; }
}
public class Trainee
{
public int TraineeId { get; set; }
public string Name { get; set; }
}
public class SessionController : Controller
{
// GET: Session
public ActionResult Index()
{
List<Session> sessions = new List<Session>();
sessions.Add(new Session { SessionId = 1, Name = "Session 1"});
sessions.Add(new Session { SessionId = 1, Name = "Session 2" });
sessions.Add(new Session { SessionId = 1, Name = "Session 3" });
return View(sessions);
}
}
}
namespace WebApplication1.Controllers
{
public class TraineeController : Controller
{
public ActionResult Add(int sessionid)
{
List<Session> sessions = new List<Session>();
sessions.Add(new Session { SessionId = 1, Name = "Session 1" });
sessions.Add(new Session { SessionId = 1, Name = "Session 2" });
sessions.Add(new Session { SessionId = 1, Name = "Session 3" });
var session = sessions.FirstOrDefault(c => c.SessionId == sessionid);
ViewBag.session = session;
return View();
}
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Индекс сеанса (Index.cshtml)
@model IEnumerable<WebApplication1.Controllers.Session>
@{
ViewBag.Title = "List Sessions";
}
<table>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<a href="/trainee/add?sessionid=@item.SessionId">Add Trainee</a>
</td>
</tr>
}
</table>
Добавить представление обучаемого (Add.cshtml)
@model WebApplication1.Controllers.Trainee
@{
var session = ViewBag.session;
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Add Trainee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
<label class="control-label col-md-2" for="Name">Session Name</label>
<div class="col-md-10">@session.Name</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}