MVC - нужна помощь для создания "Редактировать" Просмотр - PullRequest
0 голосов
/ 09 июля 2020

нужна помощь по созданию режима редактирования. Я сделал режим создания, и мне иногда нужно иметь возможность редактировать свою запись. Я использовал структуру сущностей для подключения к sql.

```
    public ActionResult Create()

    {
        List<Country> CountryList = db.Countries.ToList();
        ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");

        return View();

    }






    [HttpPost]
    [ValidateAntiForgeryToken]

    public ActionResult Create(CountryStateContactViewModel csvm)


    {

        if (!ModelState.IsValid)

        {

            return View(csvm);

        }
        Contact model = new Contact() { CountryId = csvm.CountryId, StateId = csvm.StateId, ContactId = csvm.ContactId, ImeOsobe = csvm.ImeOsobe, PrezimeOsobe = csvm.PrezimeOsobe, Komentar = csvm.Komentar, Email = csvm.Email, Aktivan = csvm.Aktivan, kcbr = csvm.kcbr, KucniBroj = csvm.KucniBroj, NazivUlice = csvm.NazivUlice, NazivNaselja = csvm.NazivNaselja, PostanskiBroj = csvm.PostanskiBroj, KontaktBroj = csvm.KontaktBroj };
        db.Contacts.Add(model);

        try
        {
            db.SaveChanges();
        }
        catch (System.Data.Entity.Validation.DbEntityValidationException db)
        {
            Exception raise = db;
            foreach (var validationErrors in db.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    string message = string.Format("{0}:{1}",
                        validationErrors.Entry.Entity.ToString(),
                        validationError.ErrorMessage);

                    raise = new InvalidOperationException(message, raise);
                }
            }
            throw raise;

        }
        return RedirectToAction("Index");

Это Create View, где я добавляю новый контакт из CountryStateContactViewModel (все три таблицы в одном VIEW с двумя подключенными раскрывающимися списками)

    @model AkvizicijeApp_4_2.Models.CountryStateContactViewModel





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

    <div class="form-horizontal">
    <h4>CountryStateContactViewModel</h4>
    <hr />

       @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
       @Html.LabelFor(model => model.CountryId, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
       @Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select 
     Country--", new { @class = "form-control" })
       @Html.ValidationMessageFor(model => model.CountryId, "", new { @class = "text-danger" })
</div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.StateId, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.StateId, "", new { @class = "text-danger" })
</div>
    <div class="form-group">
        @Html.LabelFor(model => model.ContactId, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.ContactId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ContactId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.PostanskiBroj, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.PostanskiBroj, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.PostanskiBroj, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.NazivNaselja, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.NazivNaselja, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.NazivNaselja, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.NazivUlice, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.NazivUlice, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.NazivUlice, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.KucniBroj, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.KucniBroj, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.KucniBroj, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.kcbr, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.kcbr, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.kcbr, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Aktivan, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="checkbox">
                @Html.EditorFor(model => model.Aktivan)
                @Html.ValidationMessageFor(model => model.Aktivan, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ImeOsobe, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.ImeOsobe, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ImeOsobe, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.PrezimeOsobe, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.PrezimeOsobe, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.PrezimeOsobe, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.KontaktBroj, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.KontaktBroj, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.KontaktBroj, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
        </div>
    </div>

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

    <div>
@Html.ActionLink("Back to List", "Index")
    @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    }
    <script src="~/Scripts/jquery-3.3.1.min.js"></script>
    <script>


$(document).ready(function () {
    $("#CountryId").change(function () {
        $.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
            $("#StateId").empty();
            $.each(data, function (index, row) {
                $("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + " 
     </option>")
            });
        });
    })
});
    </script>

И, наконец, CountryStateContactViewModel, где идентификаторы из первых двух таблиц (раскрывающиеся списки) и все поля из третьей таблицы.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace AkvizicijeApp_4_2.Models
    {
     public class CountryStateContactViewModel
    {
     public int CountryId { get; set; }

    public int StateId { get; set; }

    public int ContactId { get; set; }
    public int PostanskiBroj { get; set; }
    public string NazivNaselja { get; set; }
    public string NazivUlice { get; set; }
    public string KucniBroj { get; set; }
    public string kcbr { get; set; }
    public bool Aktivan { get; set; }
    public string ImeOsobe { get; set; }
    public string PrezimeOsobe { get; set; }
    public string KontaktBroj { get; set; }
    public string Email { get; set; }
    public string Komentar { get; set; }


}
    }

Пожалуйста, помогите мне с этим кодом (из Create View), чтобы сделать Edit View (где я могу изменять записи)

Большое спасибо. ;)

1 Ответ

0 голосов
/ 09 июля 2020

Режим редактирования почти такой же ... единственное отсутствующее свойство - это Id:

public class EditStateContactViewModel : CountryStateContactViewModel
{
    public int Id {get;set;}
}

public ActionResult Edit(int Id)
{
    List<Country> CountryList = db.Countries.ToList();
    ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
    ViewBag.Id = Id;
    return View();

}

[HttpPost]
[ValidateAntiForgeryToken]

public ActionResult Edit(EditStateContactViewModel csvm)
{

    if (!ModelState.IsValid)
        return View(csvm);
    
    var item = db.Contacts.First(x=>x.Id = csvm.Id);
    item.CountryId = csvm.CountryId;
    item.StateId = csvm.StateId;
    item.ImeOsobe = csvm.ImeOsobe;
    item.PrezimeOsobe= csvm.PrezimeOsobe;
    item.Komentar = csvm.Komentar ;
    item.Email = csvm.Email;
    item.Aktivan = csvm.Aktivan ;
    item.kcbr = csvm.kcbr;
    item.KucniBroj = csvm.KucniBroj;
    item.NazivUlice = csvm.NazivUlice ;
    item.NazivNaselja = csvm.NazivNaselja ;
    item.PostanskiBroj = csvm.PostanskiBroj ;
    item.KontaktBroj = csvm.KontaktBroj ;

    db.Contacts.Update(item);

    try
    {
        db.SaveChanges();
    }
    catch (System.Data.Entity.Validation.DbEntityValidationException db)
    {
        Exception raise = db;
        foreach (var validationErrors in db.EntityValidationErrors)
        {
            foreach (var validationError in validationErrors.ValidationErrors)
            {
                string message = string.Format("{0}:{1}",
                    validationErrors.Entry.Entity.ToString(),
                    validationError.ErrorMessage);

                raise = new InvalidOperationException(message, raise);
            }
        }
        throw raise;

    }
    return RedirectToAction("Index");

And View:

@model AkvizicijeApp_4_2.Models.EditStateContactViewModel 
@using (Html.BeginForm())
    {
    @Html.HiddenFor(x=>x.Id)
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
    <h4>Edit CountryStateContactViewModel</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
   @Html.LabelFor(model => model.CountryId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
   @Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select 
 Country--", new { @class = "form-control" })
   @Html.ValidationMessageFor(model => model.CountryId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.StateId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
        @Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.StateId, "", new { @class = "text-danger" })
</div>


@section Scripts 
{
    @Scripts.Render("~/bundles/jqueryval")
}
    <script src="~/Scripts/jquery-3.3.1.min.js"></script>
    <script>
$(document).ready(function () {
$("#CountryId").change(function () {
    $.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
        $("#StateId").empty();
        $.each(data, function (index, row) {
            $("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + " 
 </option>")
        });
    });
})
});
</script>
...