Ich bin neu bei MVC. Mit dem Scaffolding-Mechanismus habe ich es geschafft, CRUD-Operationen für die Datenbanktabelle zu erstellen. Dies funktioniert gut, wenn Sie gleichzeitig an einem einzelnen MVC-Modell arbeiten (einem einzelnen Modell zugeordnet). Ich möchte das Hinzufügen und Bearbeiten einer Liste in die Datenbank implementieren (die Liste ist anfangs leer), der Benutzer sollte in der Lage sein, so viele Elemente hinzuzufügen, wie er benötigt, und dann die Daten an die Datenbank zu übermitteln. Ich möchte, dass diese Liste eine dynamische Länge hat, so dass der Benutzer, wenn er die Daten bearbeitet, in der Lage sein sollte, einige weitere neue Elemente in das Modell aufzunehmen und auch einige einzelne Modelle zu löschen. Ich konnte keine geeignete Ressource finden, um eine Lösung zu finden. Kleine Hilfe wird sehr geschätzt.
Szenario - Person kann mehrere Adressen haben oder Person wird keine Adressen haben. Wie fügen Sie mehrere Adressen hinzu, indem Sie der Ansicht Adressen hinzufügen und wie bearbeiten Sie diese Adressen? Wenn eine der Adressen gelöscht werden muss, wie geht das?
Vielen Dank.
Hier ist meine Ansicht:
@model MVC.Models.PersonDetailsViewModel
@{
ViewBag.Title = "AddorEdit";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="container">
<div id="personDetails" class="row">
@Html.HiddenFor(model => model.personModel.PersonId, new { @id = "personId" })
<div class="form-group">
<div class="col-md-2">
<label>First Name</label>
<div style="display:inline">
@Html.EditorFor(model => model.personModel.FirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.personModel.FirstName, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-md-2">
<label>Last Name</label>
<div style="display:inline;">
@Html.EditorFor(model => model.personModel.LastName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.personModel.LastName, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-md-2">
<label>Date of Birth</label>
<div style="display:inline">
@Html.EditorFor(model => model.personModel.DateOfBirth, new { @id = "dob", htmlAttributes = new { @class = "form-control date-picker" } })
@Html.ValidationMessageFor(model => model.personModel.DateOfBirth, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-md-1">
<label>Height</label>
<div style="display:inline">
@Html.EditorFor(model => model.personModel.Height, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.personModel.Height, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-md-1">
<label>Weight</label>
<div style="display:inline">
@Html.EditorFor(model => model.personModel.Weight, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.personModel.Weight, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-md-2">
<label>Location</label>
<div style="display:inline">
@Html.EditorFor(model => model.personModel.Location, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.personModel.Location, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
<br />
<div id="tabs" class="panel panel-default">
<div class="panel-heading">
<ul class="nav nav-tabs">
<li class="active"><a href="#tabs-1" data-toggle="tab">Address</a></li>
<li><a href="#tabs-2" data-toggle="tab">Insuarance</a></li>
<li><a href="#tabs-3" data-toggle="tab">Emergency Contacts</a></li>
</ul><br />
</div>
<div class="tab-content panel-body">
<div id="tabs-1" class="tab-pane fade in active">
<div style="height:22px">
<a class="btn btn-default" id="btnAdd" style="float:right"><span class="glyphicon glyphicon-plus-sign"></span> Add New Row</a>
</div>
<br />
<div id="mainContent">
<div id="addressDiv">
<div class="col-md-11">
@*@Html.Partial("_Address", Model.addressModel);*@
@{
Html.RenderAction("AddressPartialView", "Person");
}
</div>
<a id="closeAddress" style="margin-top:33px" class="col-md-1 closeLink"><i class="glyphicon glyphicon-trash" style="color:red"></i></a>
</div>
</div>
</div>
<div id="tabs-2" class="tab-pane fade">
@Html.HiddenFor(model => model.insuranceModel.InsuranceId, new { @id = "insuranceId" })
<div class="col-md-4">
<label>Health Plan</label>
<div style="display:inline">
@Html.TextBoxFor(model => model.insuranceModel.HealthPlan, null, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.insuranceModel.HealthPlan, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-md-4">
<label>Health Plan Type</label>
<div style="display:inline">
@Html.TextBoxFor(model => model.insuranceModel.HealthPlanType, null, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.insuranceModel.HealthPlanType, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-md-4">
<label>Card Number</label>
<div style="display:inline">
@Html.TextBoxFor(model => model.insuranceModel.CardNumber, null, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.insuranceModel.CardNumber, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div id="tabs-3" class="tab-pane fade">
@Html.HiddenFor(model => model.emergencyContactModel.EmergencyContactId, new { @id = "emergencyContactId" })
<div class="col-md-3">
<label>Contact Patient</label>
<div style="display:inline">
@{
List<SelectListItem> personItems = new List<SelectListItem>();
personItems.Add(new SelectListItem { Text = "--Select One--", Value = "", Selected = true });
personItems.Add(new SelectListItem { Text = "1", Value = "1" });
personItems.Add(new SelectListItem { Text = "2", Value = "2" });
personItems.Add(new SelectListItem { Text = "3", Value = "3" });
personItems.Add(new SelectListItem { Text = "4", Value = "4" });
}
@Html.DropDownListFor(model => model.emergencyContactModel.ContactPersonId, personItems, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.emergencyContactModel.ContactPersonId, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-md-3">
<label>Relationship Type</label>
<div style="display:inline">
@{
List<SelectListItem> relationshipItems = new List<SelectListItem>();
relationshipItems.Add(new SelectListItem { Text = "--Select One--", Value = "", Selected = true });
relationshipItems.Add(new SelectListItem { Text = "Father", Value = "Father" });
relationshipItems.Add(new SelectListItem { Text = "Mother", Value = "Mother" });
relationshipItems.Add(new SelectListItem { Text = "Son", Value = "Son" });
relationshipItems.Add(new SelectListItem { Text = "Daughter", Value = "Daughter" });
relationshipItems.Add(new SelectListItem { Text = "Guardian", Value = "Guardian" });
}
@Html.DropDownListFor(model => model.emergencyContactModel.RelationshipType, relationshipItems, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.emergencyContactModel.RelationshipType, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-md-3">
<label>Contact Number</label>
<div style="display:inline">
@Html.TextBoxFor(model => model.emergencyContactModel.ContactNumber, null, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.emergencyContactModel.ContactNumber, "", new { @class = "text-danger" })
</div>
</div>
<div class="col-md-3">
<label>Email Id</label>
<div style="display:inline">
@Html.TextBoxFor(model => model.emergencyContactModel.EmailId, null, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.emergencyContactModel.EmailId, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
<br />
<div class="col-md-12">
<input type="submit" value="Save" class="btn btn-default" style="margin-top:10px" />
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Und hier sind meine Controller-Methoden:
public ActionResult AddressPartialView()
{
var _model = new PersonDetailsViewModel();
return PartialView("_Address", _model.addressModel);
}
//To load the data into the form - for editing
public ActionResult AddorEdit(int id = 0)
{
if (id == 0)
{
var myModel = new PersonDetailsViewModel();
return View(myModel);
}
else
{
HttpResponseMessage responsePerson = GlobalVariables.WebApiClient.GetAsync("Person/" + id.ToString()).Result;
HttpResponseMessage responseAddress = GlobalVariables.WebApiClient.GetAsync("Address/" + id.ToString()).Result;
HttpResponseMessage responseInsurance = GlobalVariables.WebApiClient.GetAsync("Insurance/" + id.ToString()).Result;
HttpResponseMessage responseEmergencyContact = GlobalVariables.WebApiClient.GetAsync("EmergencyContact/" + id.ToString()).Result;
var personJsonString = responsePerson.Content.ReadAsStringAsync();
var deserializedPerson = JsonConvert.DeserializeObject<IEnumerable<MvcPersonModel>>(personJsonString.Result);
var addressJsonString = responseAddress.Content.ReadAsStringAsync();
var deserializedAddress = JsonConvert.DeserializeObject<IEnumerable<MvcAddressModel>>(addressJsonString.Result);
var insuranceJsonString = responseInsurance.Content.ReadAsStringAsync();
var deserializedInsurance = JsonConvert.DeserializeObject<IEnumerable<MvcInsuranceModel>>(insuranceJsonString.Result);
var emergencyContactJsonString = responseEmergencyContact.Content.ReadAsStringAsync();
var deserializedEmergencyContact = JsonConvert.DeserializeObject<IEnumerable<MvcEmergencyContactModel>>(emergencyContactJsonString.Result);
var _ViewModel = new PersonDetailsViewModel();
_ViewModel.personModel = deserializedPerson.FirstOrDefault();
_ViewModel.addressModel = deserializedAddress.FirstOrDefault();
_ViewModel.insuranceModel = deserializedInsurance.FirstOrDefault();
_ViewModel.emergencyContactModel = deserializedEmergencyContact.FirstOrDefault();
return View(_ViewModel);
}
}
//Posting data to the database
[HttpPost]
public ActionResult AddorEdit(PersonDetailsViewModel viewModel)
{
HttpResponseMessage responsePerson = GlobalVariables.WebApiClient.PostAsJsonAsync("Person", viewModel.personModel).Result;
HttpResponseMessage responseAddress = GlobalVariables.WebApiClient.PostAsJsonAsync("Address", viewModel.addressModel).Result;
HttpResponseMessage responseInsurance = GlobalVariables.WebApiClient.PostAsJsonAsync("Insurance", viewModel.insuranceModel).Result;
HttpResponseMessage responseEmergencyContact = GlobalVariables.WebApiClient.PostAsJsonAsync("EmergencyContact", viewModel.emergencyContactModel).Result;
return RedirectToAction("Index");
}
Ich verwende die Web-API für den Backend-Prozess. Ich habe in der Ansicht für die Registerkarte Adresse eine Schaltfläche zum Löschen und zum Hinzufügen einer neuen Zeile hinzugefügt. Im Moment arbeitet es nur mit einem einzigen Modell, ich wollte wissen, wie es für eine dynamische Liste implementiert wird. So kann eine Person eine Anzahl von Adressen haben und er kann bearbeiten, was er will und auch basierend auf AddressId löschen . Ich weiß, dass der Code ziemlich niedrig erscheint. Sie möchten nur die Syntax und die Semantik kennen, um mit List zu arbeiten. Tut mir leid, dass ich die Dinge durcheinander gebracht habe. Vielen Dank.
Habe eine Lösung von Matt Lunn.
Folgen Sie diesem Link: - https://www.mattlunn.me.uk/blog/2014/08/how-to-dynamically-via-ajax-add-new-items-to-a-bound-list-model-in -asp-mvc-net /
Sie wird implementiert, indem Sie die benutzerdefinierte HtmlHelper- Erweiterung verwenden und Html.EditorForMany () erstellen.
Vielen Dank für den Trick Matt Lunn . Funktioniert genau wie ich wollte. :)