aim trying to create my first web asp net mvc app and i have a problem at the very beginning=(
I have a db model, it's quite simple:
I have a Visitor class:
public class Visitor {
public int Id {get; set;}
public int Name {get; set;}
public int RequestId {get; set;}
public virtual Request Request{get; set;}
}
And a Request class:
public class Request {
public int Id {get; set;}
public DateTime VisitDate {get; set;}
public ICollection<Visitor> Visitors {get; set;}
}
All i want for now is to be able to create and edit Requests in such a forms, where i can modify the request's Visitors navigation property.
In my controller:
[HttpGet]
public ActionResult Edit(int id)
{
var request = db.Requests.Find(id);
return View(request);
}
[HttpPost]
public ActionResult Edit(Request request, string[] visitors)
{
if (ModelState.IsValid)
{
db.Entry(request).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(request);
}
The string[] visitors
parameter is my 10000s try to figure out how the hell should i pass Visitors collection back to my controller. I tried to use a ViewModel with two fields = Request
and ICollection<Visitor>
- nothing helpes. Visitors are always null back in my controller.
Here is my view:
<div class="form-horizontal">
<h4>Request</h4>
@Html.HiddenFor(model => model.Id)
<div class="form-group">
<label>Visitors</label>
@foreach (var v in Model.Visitors)
{
@Html.HiddenFor(x =>v.Id)
@Html.TextBoxFor(x => v.Name, new {@class="form-control", name = "visitors"})
}
</div>
<div class="form-group">
@Html.LabelFor(model => model.Created, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Created, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Yes, I know that "name=visitors"
is wrong. I just cant' find the RIGHT way to do it. Can somebody please tell me WHAT EXACTLY am i doing wrong? I just want to be able to edit visitors of request, is it a big deal or something?
Thanks.