2
Continuing the previous topic (User add date to List MVC 4) I have a new question. You can see in this topic the initial question and the answer that I was given, but I needed to answer it but I am not allowed. Following the user response, I created this code:
public ActionResult Create()
{
ViewBag.EnrollmentId = new SelectList(db.Enrollments, "EnrollmentId", "Name");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Component component)
{
if (ModelState.IsValid)
{
db.Components.Add(component);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.EnrollmentId = new SelectList(db.Enrollments, "EnrollmentId", "Name", componente.EnrollmentId);
return View(component);
}
public ActionResult CreateByEnrollmentId(int id)
{
var enrollment = db.Enrollments.FirstOrDefault(e => e.EnrollmentId == id);
if (enrollment == null)
return HttpNotFound();
var component = new Component
{
EnrollmentId = enrollment.EnrollmentId
};
return View("Create", component);
}
However when I create a Component it actually passes the id (it says Components/create/1 for example) but still gives the error ""The Enrollmentid field is required." Can anyone help me? Thank you
Edit: View Create
@model PFC.Models.Component
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Component</legend>
<div class="editor-field">
@Html.HiddenFor(model => model.EnrollmentId)
@Html.ValidationMessageFor(model => model.EnrollmentId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
On the line
db.Components.Add(component);
, what values it has in the objectcomponent
?– Thiago Lunardi
Also post your View Create.
– Randrade
I edited with the create view. The values you have in the Component object are Enrollmentid and Name
– dasdasd
I think you are using the site wrong here. You could have edited your previous question or opened a new question with the previous user. Anyway, I’ll try to answer.
– Leonel Sanches da Silva