/ / jak zapisać wiele wybranych wartości pola wyboru do bazy danych mvc - jquery, sql-server, asp.net-mvc, asp.net-mvc-4, pole wyboru

jak zapisać wiele wybranych wartości pola wyboru do bazy danych mvc - jquery, sql-server, asp.net-mvc, asp.net-mvc-4, pole wyboru

Pracuję nad projektem MVC i mamzadanie, aby zaznaczyć więcej niż jeden element w polu wyboru i chcesz zapisać te wybrane elementy do bazy danych. W tym celu stworzyłem trzy stoliki. Pierwszy to DistrictMaster

public partial class DistrictMaster
{
public int Id { get; set; }
public string DistrictName { get; set; }
public virtual ICollection<PostMaster> PostMasters { get; set; }
}

Tutaj wchodzę do różnych dzielnic, a to zapisuje do bazy danych druga tabela PostMaster

 public partial class PostMaster
{
public int Id { get; set; }
public string PostName { get; set; }
public string PIN { get; set; }
public Nullable<int> DistrictID { get; set; }

public virtual DistrictMaster DistrictMaster { get; set; }
}

tutaj wchodzę w inny post na podstawie dzielnicy wybranej z rozwijanej listy. Identyfikator Dystryktu jest kluczem obcym i zapisze kod PIN i nazwy do odpowiedniej dzielnicy w tabeli

Trzecia tabela to AgentPostMapping

  public partial class AgentPostMapping
{
public int Id { get; set; }
public Nullable<int> AgentId { get; set; }
public Nullable<int> PostId { get; set; }
public Nullable<System.DateTime> EffectDate { get; set; }
}

Tutaj PostId nie jest kluczem obcym i muszę zapisać zaznaczone lub zaznaczone elementy w polu wyboru jako interger do tego postId. To jest ta część, w której mam kłopot.

kontroler

 public ActionResult Create()
{
ViewBag.AgentId = new SelectList(db.AgentMasters, "ID", "FirstName");
ViewBag.DistrictId = new SelectList(db.DistrictMasters, "Id", "DistrictName");
return View();
}

public JsonResult GetPosts(string id)
{
List<SelectListItem> posts = new List<SelectListItem>();
var postList = this.Getpost(Convert.ToInt32(id));
ViewBag.Postdata= this.Getpost(Convert.ToInt32(id));
var postData = postList.Select(m => new SelectListItem()
{
Text = m.PostName,
Value = m.Id.ToString(),
});
return Json(postData, JsonRequestBehavior.AllowGet);
}

public IList<PostMaster> Getpost(int DistrictId)
{
return db.PostMasters.Where(m => m.DistrictID == DistrictId).ToList();
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,AgentId,PostId,EffectDate")] AgentPostMapping agentPostMapping, FormCollection formdata)
{
if (ModelState.IsValid)
{
db.AgentPostMappings.Add(agentPostMapping);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}

ViewBag.AgentId = new SelectList(db.AgentMasters, "ID", "FirstName", agentPostMapping.AgentId);
return View(agentPostMapping);
}

To jest moja część kontrolera I nie napisałem kodu w [HttpPost]. Czy ktoś może mi pomóc napisać kod, aby zapisać do db.

wyświetl (utwórz)

@model BeyondThemes.BeyondAdmin.Models.AgentPostMapping

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.AgentId,"AgentName", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("AgentId", null, "select", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.AgentId, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.Label("District", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("DistrictId", ViewBag.DistrictId as SelectList, "-- Please Select  --", new { style = "width:250px" })
@*@Html.DropDownList("DistrictID", null, "select", htmlAttributes: new { @class = "form-control" })*@
@*@Html.ValidationMessageFor(model => model.PostMaster.DistrictID, "", new { @class = "text-danger" })*@
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.PostId,"PostName", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div id="PostMaster"></div>
@Html.ValidationMessageFor(model => model.PostId, "", 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>

}

<script type="text/javascript">
$(document).ready(function () {
//District Dropdown Selectedchange event
$("#DistrictId").change(function () {
$("#PostMaster").empty();
$.ajax({
type: "POST",
url: "@Url.Action("GetPosts")", // Calling json method
dataType: "json",
data: { id: $("#DistrictId").val() },
// Get Selected post id.
success: function (posts) {
$.each(posts, function (i, post) {
//$("#PostMaster").append("<option value="" + post.Value + "">" +
//    post.Text + "</option>");

$("#PostMaster").append("<input type="checkbox" name="postdata">" + post.Text+"<br>");
});
},
error: function (ex) {
alert("Failed to retrieve post." + ex);
}
});
return false;
})
});

To jest zrzut ekranu pokazujący, jak strona ma wyglądać

wprowadź opis obrazu tutaj

Kiedy kliknę przycisk Utwórz, zaznaczając pole wyboru, zaznaczone pole wyboru nie występuje w [HttpPost] parametru create

to pokazuje tak

wprowadź opis obrazu tutaj

dlaczego ta wartość nie jest wyświetlana w PostId. Czy ktoś może mi pomóc znaleźć rozwiązanie tego problemu. Jak mogę to rozwiązać?

Odpowiedzi:

0 dla odpowiedzi № 1

Wszystko wydaje się być w porządku Rozwiązaniem twojego problemu jest to, że możesz uzyskać wartość elementu za pomocą atrybutu name. albo zmień atrybut nazwy name = "postdata" do name = "PostId" w jquery, gdzie próbujesz dodać pole wyboru.

lub możesz zmienić nazwę właściwości w modelu PostID do postdta


0 dla odpowiedzi nr 2

Myślę, że powinieneś stworzyć input z nazwą "PostId".

widzę @Html.LabelFor i a @Html.ValidationMessageFor, ale gdzie jest EditorFor?

Nie musisz używać HTML-Helper, gdzieś musi być input (pole wyboru) z nazwą "PostId"