简体   繁体   English

MVC,以表单形式获取现有数据的编辑视图问题

[英]MVC, Edit View problem with getting existing data in form

I got a problem when I create edit view.创建编辑视图时出现问题。 I run program, from index view and click on edit on some data.我从索引视图运行程序并单击编辑某些数据。 Issuse is that Im getting empty form(I can save it to database normaly) but I want to see what I entered and than edit some parts of data and save it.问题是我得到了空表单(我可以正常将其保存到数据库中),但我想查看我输入的内容,而不是编辑某些数据部分并保存它。

    public ActionResult Edit(int Id)
    {
        IEnumerable<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);
        }

        Contact item = db.Contacts.First(x => x.ContactId == csvm.ContactId);
        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;         
        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");
    }

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

And View并查看

   @model AkvizicijeApp_4_2.Models.EditStateContactViewModel

   <div class="form-horizontal">
    <h4>CountryStateContactViewModel</h4>
    <hr />
    <h2>Edit</h2>
    @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>

    <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>

..... ......

and scripts from View for Parent-Child dropdown lists和来自 View for Parent-Child 下拉列表的脚本

  @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>

You didn't select existing data to edit form.您没有 select 现有数据来编辑表单。 You need to load your DB data to viewmodel and pass your viewmodel to cshtml by return View(vm):您需要将数据库数据加载到 viewmodel 并通过 return View(vm) 将 viewmodel 传递给 cshtml:

[HttpGet]
public ActionResult Edit(int Id)
{
    IEnumerable<Country> CountryList = db.Countries.ToList();
    ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
    ViewBag.Id = Id;

    var item = db.Contacts.First(x => x.ContactId == Id);
    var vm = new EditStateContactViewModel();
    vm.Id = Id;
    vm.NazivNaselja = item.NazivNaselja;
    ...

    return View(vm);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM