我该如何通过管理员视图更新价格?我的费率会随着时间变化。我如何允许管理员更新它们并相应地向用户显示?

时间:2018-11-25 13:26:59

标签: asp.net-mvc

这是我的代码,我使用asp.net Web应用程序MVC

基本上,只需要允许admin / superuser能够更新这两个文本框名称的有效期和年利率中的会员费率,当单击其续约时间时,它将在非管理员视图中的“价格”中显示。如果有人可以帮助我提供这些代码,那就太好了。

此视图使管理员可以更新年度和终身会员费的价格

 @model RenewMember
@{
    ViewData["Title"] = "Membership Renewal";
    Layout = "~/Views/Shared/_Layout.cshtml";

    string msg = ViewData["msg"] as string;

    var Duration = new[]
    {
        new { value=1, text="1 year"},
        new { value=2, text="2 years"},
        new { value=3, text="3 years"},
        new { value=4, text="Life-time"}
    };

    @section ScriptSection {
        <script>
            function DisplayPrice() {
                var price1yearmember = 100;
                var rate = 1;
                var subtotal = 0;
                if (selectedCurrency == "USD") {
                    subtotal = price1yearmember * rateUSD;
                }
                else if (selectedCurrency == "MYR") {
                    subtotal = price1yearmember * rateMYR;
                }
                else if (selectedCurrency == "SGD") {
                    subtotal = price1yearmember * rate;
                }
                $("#txtPrice").val(subtotal.toFixed(2));
            }

        </script>
    }
}

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Contact Us</title>
    <link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.min.js"></script>
    <link href="~/lib/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
    <script src="~/lib/moment/min/moment.min.js"></script>
    <script src="~/lib/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js"></script>
    <script type='text/javascript' src='https://www.google.com/recaptcha/api.js?onload=recaptchaCallback&#038;render=explicit&#038;ver=2.0'></script>

    <style>
        <style > .input-group-addon {
            cursor: pointer;
        }

        #BsDateTimePicker {
            cursor: pointer;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            $('#BsDateTimePicker').datetimepicker({
                format: 'YYYY-MM-DD'
            });
        });
    </script>
    <script src="~/lib/jquery-validation/src/core.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
    <meta charset="utf-8" />
    <title>Contact Us</title>
    <style type="text/css">
        #head {
            font-family: 'Times New Roman', Times, serif;
            font-style: oblique;
            font-size: larger;
            text-align: center;
            color: black;
            will-change: contents;
            font-weight: 900;
        }

        #late {
            font-family: 'Times New Roman', Times, serif;
            font-style: italic;
            font-size: larger;
            text-align: center;
            color: black;
            will-change: contents;
        }

        .field-validation-error {
            font-weight: bold;
            color: red;
            /*background-color: yellow;*/
            font-family: 'Times New Roman', Times, serif;
            font-style: unset;
            font-size: medium;
        }

        .validation-summary-errors {
            border: 2px dashed red;
            color: red;
            /*background-color: yellow;*/
            font-weight: bold;
            margin: 12px;
        }
    </style>
</head>

<form class="form-horizontal" asp-action="RenewMember">

    @if (User.IsInRole("Admin") || User.IsInRole("SuperUser"))
    {

        <div class="form-group">
            <label input id="txtYearRate" class="control-label col-sm-3" asp-for="YearlyRate">Rates per year : </label>
            <div class="col-sm-5">
                <input asp-for="YearlyRate" class="form-control" />
            </div>
            <div class="has-error">
                <span asp-validation-for="YearlyRate" class="text-danger"></span>
            </div>
        </div>



        <div class="form-group">
            <label input id="txtLifeRate" class="control-label col-sm-3" asp-for="LifeRate">Rates for Lifetime membership : </label>
            <div class="col-sm-5">
                <input asp-for="LifeRate" class="form-control" />
                </div>
            <div class="has-error">
                <span asp-validation-for="LifeRate" class="text-danger"></span>
            </div>
        </div>

    }
    else
    {
        <div class="form-group">
            <label class="control-label col-sm-3" asp-for="Email">Email : </label>
            <div class="col-sm-5">
                <input asp-for="Email" class="form-control" />
            </div>
            <div class="has-error">
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
        </div>

        <div class="form-group">
            <label class="control-label col-sm-3" asp-for="RenewDuration">Duration : </label>
            <div class="col-sm-4">
                @foreach (var freq in Duration)
                {
                    <input type="radio" asp-for="RenewDuration" value="@freq.value" /> @freq.text
                }
            </div>
            <div class="has-error">
                <span asp-validation-for="RenewDuration" class="text-danger"></span>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">Price: </label>
            <div class="col-sm-6" style="padding-right:15px;">
                <input id="txtPrice" class="form-control" value="-" readonly disabled style="background-color:#C0C0C0" />
            </div>
            <div class="col-sm-1" style="padding-left:0">
                @{
                    Html.RenderPartial("_CurrencySelector");
                }
            </div>
        </div>

                    }

@if (User.IsInRole("Admin") || User.IsInRole("SuperUser"))
{
    <div class="form-group">
        <div class="col-sm-offset-3 col-sm-6">
            <input type="submit" class="btn btn-primary" value="Save" />
        </div>
    </div>
}
else
{
    <div class="form-group">
        <div class="col-sm-offset-3 col-sm-6">
            <input type="submit" class="btn btn-primary" value="Renew" />
        </div>
    </div>

}


</form>

这是我的模型代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace PSS.Models
{
    public class RenewMember
{


    [DataType(DataType.EmailAddress)]
    [Required(ErrorMessage = "Required Field")]
    public string Email { get; set; }

    [Range(1, 4, ErrorMessage = "Please select a Duration for renewal")]
    public int RenewDuration { get; set; }

    [Required(ErrorMessage = "Required Field")]
    public int YearlyRate { get; set; }

    [Required(ErrorMessage = "Required Field")]
    public int LifeRate { get; set; }

    public string Currency { get; set; }
    public float CurrencyRate { get; set; }
}
}

这将是我的控制器,里面没有太多东西

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using PSS.Models;
using System.Security.Claims;
using System.Data;
using Microsoft.EntityFrameworkCore;
using System.Text;
using System.Threading;
using System.Net.Mail;
using System.Net;
using System.Web;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using MimeKit;
using static System.Net.Mime.MediaTypeNames;
using MailKit.Net.Smtp;
using System.Linq.Dynamic;
using Microsoft.AspNetCore.Authorization;
using System.Dynamic;

namespace PSS.Controllers
{
public class RenewMemberController : Controller
{
    private AppDbContext _dbContext;

    public RenewMemberController(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public IActionResult Index()
    {
        // DbSet<RenewMember> dbs = _dbContext.RenewMember;
        //var lstType =
        //  dbs.ToList<RenewMember>()
        //   .OrderBy(p => p.TypeName)
        // .Select(
        //   p =>
        // {
        //   dynamic d = new ExpandoObject();
        // d.value = p.MemberTypeId;
        //d.text = p.TypeName;
        //return d;
        // }
        // )
        //.ToList<dynamic>();
        //ViewData["currency"] = lstCurrency;

        return View();
    }
}
}

这是我尝试过的

    [HttpPost]
    public IActionResult UpdateRate(RenewMember rate)
    {
        if (ModelState.IsValid)
        {
            DbSet<RenewMember> dbs = _dbContext.RenewMember;
            RenewMember nrate = dbs.Where(m => m.Id == rate.Id).FirstOrDefault();

            if (rate != null)
            {
                nrate.YearlyRate = rate.YearlyRate;
                nrate.LifeRate = rate.LifeRate;

                string msg = "";
                if (_dbContext.SaveChanges() == 1)
                    msg = String.Format("Rates info updated!");
                TempData["Msg"] = msg;
            }
            else
            {
                TempData["Msg"] = "Rate not found!";
                return RedirectToAction("Index");
            }
        }
        else
        {
            TempData["Msg"] = "Invalid information entered";
        }
        return RedirectToAction("Index");
    }

当我单击“保存”按钮时,它显示找不到本地主机页面,它将我重定向到不存在的“ http://localhost:49228/renewmember/RenewMember”。我的页面应该是http://localhost:49228/renewmember/Index。但是我的数据库仍然没有更新。

1 个答案:

答案 0 :(得分:0)

只需回答这个问题,您就指向RenewMember

<form class="form-horizontal" asp-action="RenewMember">

您可以考虑使用不同的控制器方法:

<form class="form-horizontal" asp-action="UpdateAdminMember">

以及使用不同控制器方法的单独视图:

<form class="form-horizontal" asp-action="SaveNewMember">

或使用一些助手

@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post))
{

关于您的管理员示例(非管理员视图的另一个局部视图)

@using (Html.BeginForm("UpdateAdminMember", "RenewMember", FormMethod.Post))
{
    @Html.LabelFor(m => m.YearlyRate)
    @Html.TextBoxFor(m => m.YearlyRate)
    ...
}