MVC在同一视图中添加用户和编辑用户

时间:2018-04-11 10:50:51

标签: c# html model-view-controller

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

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

当我单击“编辑”按钮时,我尝试返回“索引”视图(查看两个部分视图正确显示的视图),但是如何将用户ID传递给用户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>

这是UserList部分视图代码:

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

2 个答案:

答案 0 :(得分:0)

点击“编辑”按钮,您可以执行以下两项操作之一:

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

(a)从List

中获取用户的相应值

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

2-重新加载页面(不使用javascript)

(a)路线/返回Index视图

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

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

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

答案 1 :(得分:0)

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

  1. 首先用非超链接元素替换 @ Html.ActionLink ,例如div,section,...
  2. <span class="EditUser" data-id="@item.Id">edit</span>

    1. 在div中添加ID以显示部分视图,如下所示:
    2. <div id="EditUserSection">
          @{ 
              Html.RenderPartial("_UserEditPartial", user);
          }
      </div>

      1. 最后添加如下所示的JavaScript文件(包括jQuery)
      2. $(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
                }
            });
        
        });