2018-04-09 开胃学习.Net 系列 - MVC作业

【已解决】在Transaction也加上【authorize】
【已解决】需要在Account Detail里 修改 Account Transaction Details

【已解决】Balance 会根据 transaction amount 的值 减少
【已解决】
【已解决】

【未解决】 如何把Balance 传到 下一局

【未解决】如何在Check 这个地方显示 String,而不是bool
【未解决】

Transaction Create
【未解决】Transaction Balance 应该show
【未解决】输入Amount,应该直接做个减法
【未解决】Transaction Type 应该是个dropdownlist,输入值应该是bool
【未解决】最好应该是不能选 Bank Account ID
【未解决】有Cancel 按钮

Transaction Delete
【待解决】本身就不能有Delete 这个功能

【未解决】如果Account 删除了,Transaction自动看不见

  • 是不是有点像某种check,删除了就没有
  • 在 Transaction 的 Account Transaction Detail,如果没有Account就不会显示Transaction
  • 在 Transaction 的Index里,需要做排除那些IsDelete的
  • 现在得到了一个query 里面有所有的Alive的BankID
  • 我希望的是 可以取出所有活着 的 transaction ,没有ToList之前
  • 现在的问题是,我不能通过一个query数据机构用我已经知道的 linq 语言 获得 这个 活着的transactionlist

步骤:

  1. 新建,记得有Individual User

  2. BankAccount.cs

  3. Transaction.cs

  4. DAL -> Context

  5. Build Sulotion

  6. Scaffolding

  7. 修改 _Layout.cshtml

  8. 跑一边验证: BankAccount

  9. Index 改一下 标题,第一项不要是AccountUser,最后不需要写IsDeleted

  1. 通过Index 跳转的 是Transaction Index,修改外观

  2. [Remote("AccountBalanceMustBePositive", "Transactions", ErrorMessage = "The Transaction Amount Cannot be More Than Your Account Balance!")]

  • 【未完成】IsCheck没有修改成dropdownlist,而且是个bool值
  • 【未完成】点进去Detail应该是全部?
  • 【未完成】之前

01: 在route.config 里面的id 是没有constraint的,可以是数字也可以是stirng action

  1. 可以放入constraint












Hint: implement this as a form with just a submit button. Create two controller actions:
one action for GET requests, which asks the user to confirm by pressing a button. Create a
second one adorned with the [HttpPost] attribute that processes the form and performs the
“deletion” and informs the user that is has been deleted (or error, if there was an error).


































A transaction details screen (/Bank/Account/{id1}/Transaction/{id2}) where {id1} is a the account number and {id2} is the transaction number. You should validate that the transaction corresponds to the account in question. The transaction details screen should provide a “read only” 3 view of the transaction: date and time of the transaction (month, day, and year, hour and minute), description of the transaction, and the amount of the transaction expressed as a decimal (positive for deposit, negative for check). A button should take the user back to the account details screen. Users should under no circumstance be allowed to view accounts that are not theirs or transactions for accounts that are not theirs. Other requirements are as follows:

  1. 交易详情屏幕((/Bank/Account/{id1}/Transaction/{id2}),其中{id1}是账户号码,{id2}是交易号码。

这个有点不懂

  1. 您应该验证交易是否与相关账户相符。交易详情屏幕应提供交易的“只读”3视图:交易的日期和时间(月,日,年,小时和分钟),交易描述以及交易金额十进制(存款为正,支票为负)。

  2. 一个按钮应该将用户带回到帐户详细信息屏幕。在任何情况下,用户都不应允许查看不属于他们的账户或不属于他们的账户的交易。其他要求如下:

The solution must be deployed to Azure. Write the hyperlink of the site inline in your homework submission. If you had any issues deploying to Azure previously, you should make resolving those issues a priority. Do not expect last minute help.

Your models relating to users, bank accounts, and transactions must be stored in the database using Entity Framework.

Because this is a banking web site, assume all transactions are sensitive. For this reason, ensure that your site is protected against cross-site request forgeries. This is as simple as displaying the anti-forgery token in your views and validating the token in your actions. Scaffolding will likely do this for you, but it is your responsibility to ensure that the finished product contains the proper checking.

  1. cross-site request forgeries是什么?
  2. 要确保

For the purposes of this assignment, it is not necessary to tier the solutionn into layers (data store, model, business logic, UI). Everything can be kept in one project this time. However, all business logic code should be placed into a folder called “Biz Logic.” It is okay for business logic to directly perform database operations in this homework. However, it is a better design to decouple these—we will cover the topics of decoupling and dependency injection in a future lecture.

  1. 不理解这句话

A user should only be able to see their own accounts and transactions for only those accounts. Specifically, accounts that were created while they were logged into the web site under their user ID.

You don’t have to write any login functionality as part of this assignment. You can (and should) use the built-in authentication features in the template MVC site generated by Visual Studio. To do this, be sure
to specify “individual user accounts” when creating your project so that these features will be included. The Visual Studio MVC project template uses ASP.NET Identity for user management.

  1. “individual user accounts”
  2. ASP.NET Identity for user management.

You can query the unique ID of the currently logged in user with User.Identity.GetUserId().
You may maintain your own user table and reference the user ID from Identity. No foreign key is necessary between your user table and Identity’s.

  1. 这句话解决我之前的疑惑,但是我还是完全不理解
  2. [已解决] 这里我用了非常愚蠢的办法来解决,而且我觉得很不安全的是,我只是显示出了当前用户的信息。
BankAccountsController
        // GET: BankAccounts
        public ActionResult Index()
        {

            ViewBag.Message = User.Identity.GetUserId();
            return View(db.BankAccounts.ToList());
        }

        // POST: BankAccounts/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "BankAccountID,BankAccountName,BankAccountNumber,BankAccountBalance,IsDeleted")] BankAccount bankAccount)
        {
            if (ModelState.IsValid)
            {
                var currentUserId = User.Identity.GetUserId();
                db.BankAccounts.Add(bankAccount);
                bankAccount.BankAccountUser = currentUserId;
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(bankAccount);
        }

Index.cshtml
    @foreach (var item in Model)
    {
        if (ViewBag.Message == item.BankAccountUser)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.BankAccountUser)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.BankAccountName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.BankAccountNumber)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.BankAccountBalance)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.IsDeleted)
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.BankAccountID }) |
                    @Html.ActionLink("Details", "Details", new { id = item.BankAccountID }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.BankAccountID })
                </td>
            </tr>
        }
    }

Each user must log into their account to access all of the functionality described above. That is, authorization is required for all pages discussed above. At your discretion, you may choose to have additional “public” pages not described here, such as an “About” page—those types of screens do not require authorization.

You may (and should) use the scaffolding feature to create views and/or controllers as necessary, and then customize the scaffolded views and controllers, accordingly. Much of the functionality required above is provided to you “out-of-the-box” by the scaffolding feature, although you may need to make some adjustments. Inspecting the auto-generated MVC code allows you to learn how to perform typical operations in MVC.

You will need to register new routes for this assignment, so familiarize yourself with RouteConfig.cs (included in new MVC projects) and educate yourself on routing first. Consult the NYU Classes Resources folder, lectures, and demos too.
这句话也完全不懂。

The web site does not have to look beautiful. It can look “basic” as long as it is both usable and clean in appearance and function. The code should be written in a manner one would expect of a graduate computer science (or related major) student. This assignment is mostly about using the MVC features and is therefore more about the code than the screen appearance.

Make ample use of comments to inform code readers what you are trying to accomplish. Keep code short and concise












































<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    <li>@Html.ActionLink("Bank Account", "Index", "BankAccounts")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

Question Remain:

  1. 关于DatabaseGenerated特性,需要使用
  2. Code First Migration来改变数据库架构
  3. 我如何检查我的数据库建立的Entity关系是不是正确呢?
  4. 现在initializer 无法工作,我删除了之后可以工作
  5. 但是需要我写入日期?

Migration 这部分非常难做,我都是删除了一组数据库再重做的。

为什么我的 Controller都在 Model里

相关链接:
建立一个EF数据模型

Youtube - Remote validation in asp net mvc

using System.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using Bank.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace Bank.DAL
{
    public class AccountContext : DbContext
    {

        public AccountContext() : base("BankContext")
        {
        }

        public DbSet<BankAccount> BankAccounts { get; set; }
        public DbSet<Transaction> Transactions { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}

4-9 - 12:00 还是正确的版本
Transaction Controller

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Bank.DAL;
using Bank.Models;

namespace Bank.Controllers
{
    public class TransactionsController : Controller
    {
        private AccountContext db = new AccountContext();

        // GET: Transactions
        public ActionResult Index()
        {
            var transactions = db.Transactions.Include(t => t.BankAccount);
            return View(transactions.ToList());
        }

        // GET: Transactions/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Transaction transaction = db.Transactions.Find(id);
            if (transaction == null)
            {
                return HttpNotFound();
            }
            return View(transaction);
        }

        // GET: Transactions/Create
        public ActionResult Create()
        {
            ViewBag.BankAccountID = new SelectList(db.BankAccounts, "BankAccountID", "BankAccountUser");
            return View();
        }

        // POST: Transactions/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "TransactionID,TransactionDate,TransactionBalance,TransactionAmount,IsCheck,TransactionDescription,IsDeleted,BankAccountID")] Transaction transaction)
        {
            if (ModelState.IsValid)
            {


                transaction.TransactionDate = DateTime.Now;

                db.Transactions.Add(transaction);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.BankAccountID = new SelectList(db.BankAccounts, "BankAccountID", "BankAccountUser", transaction.BankAccountID);
            return View(transaction);
        }

        // GET: Transactions/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Transaction transaction = db.Transactions.Find(id);
            if (transaction == null)
            {
                return HttpNotFound();
            }
            ViewBag.BankAccountID = new SelectList(db.BankAccounts, "BankAccountID", "BankAccountUser", transaction.BankAccountID);
            return View(transaction);
        }

        // POST: Transactions/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "TransactionID,TransactionDate,TransactionBalance,TransactionAmount,IsCheck,TransactionDescription,IsDeleted,BankAccountID")] Transaction transaction)
        {
            if (ModelState.IsValid)
            {
                db.Entry(transaction).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.BankAccountID = new SelectList(db.BankAccounts, "BankAccountID", "BankAccountUser", transaction.BankAccountID);
            return View(transaction);
        }

        // GET: Transactions/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Transaction transaction = db.Transactions.Find(id);
            if (transaction == null)
            {
                return HttpNotFound();
            }
            return View(transaction);
        }

        // POST: Transactions/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Transaction transaction = db.Transactions.Find(id);
            db.Transactions.Remove(transaction);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342

推荐阅读更多精彩内容