【问题标题】:MVC Add User and Edit User in same ViewMVC 在同一个视图中添加用户和编辑用户
【发布时间】:2018-04-11 20:22:03
【问题描述】:

我有一种情况,我试图在 MVC 中创建用户管理视图,并且在同一视图中我希望能够编辑和添加新用户,但我无法弄清楚我做错了什么以及如何将在同一视图上显示用户列表和用户编辑/创建表单。

目前我有两个部分视图,一个用于在表格中显示用户列表,另一个用于显示创建/编辑表单。一切正常,除了问题是当我单击用户列表中的编辑按钮时,我返回编辑/创建表单所在的部分视图,但结果是我只显示该视图,我希望列表也成为即使当我点击编辑按钮时也会显示。

当我单击“编辑”按钮时,我尝试返回索引视图(两个部分视图都正确显示的视图),但是我将如何将用户 ID 传递给它,因为该视图已经作为用户列表返回。

这是 AccountController 代码:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using NEASports.Models;

namespace NEASports.Controllers
{
    public class AccountController : Controller
    {
        OurDBContext db = new OurDBContext();
        // GET: Account
        public ActionResult Index()
        {



                return View(db.userAccount.ToList());            



        }

        // GET Akcije za registraciju
        public ActionResult Register(int id)
        {

            return View("_UserEditPartial", db.userAccount.Find(id));

        }

        //Post Akcija za registraciju
        [HttpPost]
        public ActionResult Register(UserAccount account)
        {
            if (ModelState.IsValid)
            {
                if (account.Id <= 0)
                {

                    db.userAccount.Add(account);

                    ModelState.Clear();
                    ViewBag.Message = account.FirstName + " " + account.LastName + " uspješno registrovan.";
                }
                else
                {
                    db.Entry(account).State = EntityState.Modified;

                }
                db.SaveChanges();
                return RedirectToAction("Index");


            }

            return View(account);
        }



        // Akcije za Logon
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(UserAccount user)
        {


                    var usr = db.userAccount.FirstOrDefault(u => u.Username == user.Username && u.Password == user.Password);
                    if (usr != null)
                    {
                        Session["Id"] = usr.Id.ToString();
                        Session["Username"] = usr.Username.ToString();
                        Session["FirstName"] = usr.FirstName.ToString();
                        Session["LastName"] = usr.LastName.ToString();
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Pogrešan Username ili Password");
                    }


            return View();
        }

        public ActionResult LoggedIn()
        {
            if (Session["Id"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("Login");
            }
        }
    }
}

这是索引视图代码:

@model IEnumerable<NEASports.Models.UserAccount>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Message = "Lista korisnika";

}

@{
    NEASports.Models.UserAccount user = new NEASports.Models.UserAccount();
}

<div>

    @{ 
        Html.RenderPartial("_UserEditPartial", user);
    }


</div>

<div>
    @{
        Html.RenderPartial("_UserListPartial");
    }
</div>

这是用户列表部分视图代码:

@model IEnumerable<NEASports.Models.UserAccount>

<div class="box box-info">

    <div class="box-header with-border">
        <h3 class="box-title">@ViewBag.Message</h3>
        <div class="box-tools pull-right">
            <button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip"
                    title="Collapse">
                <i class="fa fa-minus"></i>
            </button>
            <button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">
                <i class="fa fa-times"></i>
            </button>
        </div>
    </div>
    <div class="box-body">


        <div>
            <table id="table1" class="table table-bordered table-striped">
                <thead>
                    <tr>
                        <th>@Html.DisplayNameFor(model => model.FirstName)</th>
                        <th>@Html.DisplayNameFor(model => model.LastName)</th>
                        <th>@Html.DisplayNameFor(model => model.Email)</th>
                        <th>@Html.DisplayNameFor(model => model.Username)</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var item in Model)
                    {
                        <tr>
                            <td>@Html.DisplayFor(modelItem => item.FirstName)</td>
                            <td>@Html.DisplayFor(modelItem => item.LastName)</td>
                            <td>@Html.DisplayFor(modelItem => item.Email)</td>
                            <td>@Html.DisplayFor(modelItem => item.Username)</td>
                            <td>
                                @Html.ActionLink("Edit", "Register", new { id = item.Id }) |
                                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                                @Html.ActionLink("Delete", "Delete", new { id = item.Id })
                            </td>
                        </tr>
                    }
                </tbody>
                <tfoot>
                    <tr>
                        <th>@Html.DisplayNameFor(model => model.FirstName)</th>
                        <th>@Html.DisplayNameFor(model => model.LastName)</th>
                        <th>@Html.DisplayNameFor(model => model.Email)</th>
                        <th>@Html.DisplayNameFor(model => model.Username)</th>
                        <th></th>
                    </tr>
                </tfoot>
            </table>

        </div>
    </div>
    <!-- /.box-body -->
    <div class="box-footer">
        Lista svih korisnika
    </div>
    <!-- /.box-footer-->
</div>

以及编辑用户部分视图代码:

@model NEASports.Models.UserAccount    

@{
    ViewBag.Title = "Register";
    ViewBag.Message = "Administracija Korisnika";
}

<div class="box box-danger">
    <div class="box-header with-border">
        <h3 class="box-title">@ViewBag.Message</h3>
        <div class="box-tools pull-right">
            <button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip"
                    title="Collapse">
                <i class="fa fa-minus"></i>
            </button>
            <button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">
                <i class="fa fa-times"></i>
            </button>
        </div>
    </div>
    <div class="box-body">

        @using (Html.BeginForm("Register", "Account"))
        {
        @Html.AntiForgeryToken()
        <form role="form">
            <div class="form-horizontal">


                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                @if (ViewBag.Message != null)
            {

            }
                <div class="row">
                    <div class="col-sm-6">
                        <div class="form-group">
                            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "col-sm-2 control-label" })
                            <div class="col-sm-8">
                                @Html.HiddenFor(model => model.Id)
                                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control", @placeholder = "Unesite Ime" } })
                                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
                            </div>
                        </div>

                        <div class="form-group">
                            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "col-sm-2 control-label" })
                            <div class="col-sm-8">
                                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control", @placeholder = "Unesite Prezime" } })
                                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
                            </div>
                        </div>

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

                        </div>
                    </div>


                    <div class="col-md-6">
                        <div class="form-group">
                            @Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control", @placeholder = "Unesite Username" } })
                                @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
                            </div>
                        </div>

                        <div class="form-group">
                            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", @placeholder = "Unesite Password" } })
                                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
                            </div>
                        </div>

                        <div class="form-group">
                            @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control", @placeholder = "Ponovite Password" } })
                                @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-10">
                        <div class="form-group">
                            <div class="col-sm-offset-0 col-sm-12">
                                <input type="submit" value="Sačuvaj" class="btn btn-success" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
        }

    </div>


    <!-- /.box-body -->
    <div class="box-footer">
        Otvaranje novih ili ažuriranje postojećih korisnika
    </div>
    <!-- /.box-footer-->
</div>

【问题讨论】:

    标签: c# html model-view-controller


    【解决方案1】:

    @Html.ActionLink 将重定向您想要避免的页面。 因此,要保留您的内容并仅更新特定部分,您必须使用 Ajax 调用

    1. 首先将 @Html.ActionLink 替换为非超链接元素,例如 div、section、...

    &lt;span class="EditUser" data-id="@item.Id"&gt;edit&lt;/span&gt;
    1. 在要显示部分视图的 div 中添加 ID,如下所示:

    <div id="EditUserSection">
        @{ 
            Html.RenderPartial("_UserEditPartial", user);
        }
    </div>
    1. 最后添加如下 JavaScript 文件(包括 jQuery)

    $(document).on('click', '.EditUser', function () {
    
        var id = $(this).data('id');
    
        $.ajax({
            url: "/Account/Register?id=" + id,
            cache: false,
            success: function (partialView) {
    
                $('#EditUserSection').html(partialView);
            },
            error: function (x, y, z) {
    
                // Handle Exception
            }
        });
    
    });

    【讨论】:

      【解决方案2】:

      点击编辑按钮,您可以做以下两件事之一:

      1- 无需重新加载页面(使用 javascript)

      (a) 从List 获取用户的相应值

      (b) 使用这些值填充EditUser 表单,而不重定向页面。

      2- 重新加载页面(无 javascript)

      (a) 路线/返回Index 查看

      (b) 在您的控制器中,(在加载 Index 视图之前)检查是否正在从 Edit press 调用 Index

      (c) 如果是,则抓取$_POST 数据并将其传递给EditUser 视图

      (d) 在EditUser 视图中,检查是否接收/设置了用户的任何数据。如果是,则相应地填充表单。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-17
        • 2020-06-29
        • 2010-09-06
        • 1970-01-01
        • 2017-07-13
        相关资源
        最近更新 更多