【问题标题】:MVC- need help for creating "Edit" ViewMVC-需要帮助来创建“编辑”视图
【发布时间】:2020-10-29 22:01:12
【问题描述】:

需要有关创建编辑视图的帮助。我创建了视图,有时我需要能够编辑我的条目。我使用实体框架连接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");

这是创建视图,我从 CountryStateContactViewModel 添加新联系人(一个视图中的所有三个表,带有 2 个连接的下拉列表)

    @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,前 2 个表(下拉菜单)的 id-s 和第三个表的所有字段在哪里。

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


}
    }

请帮助我使用该代码(来自创建视图)制作编辑视图(我可以在其中更改条目 )

非常感谢。 ;)

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-3 model-view-controller


    【解决方案1】:

    编辑视图几乎相同...唯一缺少的属性是 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");
    

    并查看:

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

    【讨论】:

    • 在 Controller 中,Edit Post 方法有 db.Contact.Update(item);更新带有红色下划线的地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    相关资源
    最近更新 更多