我是MVC ASP.NET 新手,我有一个处理单个事务的引导模式,我试图从模态中获取值,然后当我按下添加按钮时,我希望模态关闭,然后向控制器发送ajax帖子。控制器应处理对象的集合和单个实例,但不确定它是否完全正确。我添加了一个示例 dotnetfiddle 链接,以便更轻松地共享代码。
是否可以使用引导模式来完成以获得更好的用户体验?
我想要实现的目标: 当您通过单击"创建交易记录"添加交易记录时,当您输入日期和金额时,这些值应添加到 CustomerTransactions 集合中,并显示在窗体上,其中包含当前交易记录金额及其内容。我在 html 中添加了一个无序列表。
以下是数据结构:
视图: 只有一个带有表单、项目、html 和 jQuery 和 ajax 调用的视图
视图模型:
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class SampleViewModel
{
[Required]
[MinLength(10)]
[MaxLength(100)]
[Display(Name = "Ask Magic 8 Ball any question:")]
public string Question { get; set; }
//See here for list of answers
public string Answer { get; set; }
//Ignore the above properties for now
public int Id { get; set; }
public string Name { get; set; }
public SampleTransactionItemViewModel CustomerTransaction { get; set; }
public List<SampleTransactionItemViewModel> CustomerTransactions { get; set; }
}
public class SampleTransactionItemViewModel
{
public DateTime TransactionDate { get; set; }
public decimal TransactionAmount { get; set; }
}
}
控制器:
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class HomeController : Controller
{
private static Random _rnd = new Random();
private static List<string> _db = new List<string> {
"Yes", "No", "Definitely, yes", "I don't know", "Looks like, yes"
};
[HttpGet]
public ActionResult Index()
{
return View(new SampleViewModel());
}
/*[HttpPost]
public JsonResult GetAnswer(string question)
{
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(answer);
}*/
[HttpPost]
public ViewResult AddTransactionItem(SampleViewModel model)
{
model.CustomerTransactions.Add(model.CustomerTransaction);
model.CustomerTransaction = null;
//return PartialView("Modal/TransactionModal", output);
return View("FraudCheckBankAccountForm", model);
}
}
}
视图
@{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
p{
padding: 10px 0;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<h4>Example Adding items to collection dynamically</h4><br>
@using (Html.BeginForm())
{
<div class="form-group">
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(model => model.Name, new {@class="form-control"})
</div>
<div class="form-group">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#TransactionModal">
Create Transaction
</button>
</div>
<div class="form-group">
Current transactions
<!-- Added here dynamically-->
Transactions:
<ul>
<li>TransactionDate: Date here</li>
<li>TransactionAmount: Amount here</li>
</ul>
</div>
<br>
<button type="button" class="btn btn-success submit">Save</button>
<div class="modal fade" id="TransactionModal" tabindex="-1" role="dialog" aria-labelledby="TransactionModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Create transaction</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label class="col-md-3 control-label">Date</label>
<div class="col-md-9">
@Html.TextBoxFor(a => a.CustomerTransaction.TransactionDate, new { @class = "form-control Date", @id = "Transaction_Date", @name = "Transaction.Date", @type ="date" })
</div>
</div>
<div class="form-group NoBottomPad">
<label class="col-md-3 control-label">Amount</label>
<div class="col-md-9">
@Html.TextBoxFor(a => a.CustomerTransaction.TransactionAmount, new { @class = "form-control Amount", @id = "Transaction_Amount", @name = "Transaction.Amount"})
</div>
</div>
</div>
<div class="modal-footer">
<div class="row">
<div class="col-md-8">
<div class="hinttext" style="font-size: smaller; text-align: left; margin-left: -10px; display: table-cell; vertical-align: bottom; ">
Example
</div>
</div>
<div class="col-md-4">
<button class="btn" id="TransactionModalCancelButton" name="TransactionModalCancelButton" type="button" data-dismiss="modal">Cancel</button>
<button class="btn-default btn" id="AddTransaction" name="AddTransaction" type="button" disabled>Add</button>
</div>
</div>
</div>
</div>
</div>
</div>
}
<br/><br/>
<div class="alert alert-warning fade">
<img src="http://entechprod.blob.core.windows.net/dotnetfiddle/morpheus.jpg" style="max-width:100%;"/><br/><br/>
<strong><span class="alert-content"></span></strong>
</div>
</div>
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
function openAlert(txt) {
$('.alert-content').text(txt);
$('.alert').addClass('in');
}
function closeAlert() {
$('.alert').removeClass('in');
}
$(function(){
var answer = '@Model.Answer';
if(answer && answer != '')
openAlert(answer);
$('#Question').change(closeAlert);
$('#Question').keyup(closeAlert);
// This is the save button
var save = document.getElementById("AddTransaction");
var cancel = document.getElementById("TransactionModalCancelButton");
// This is the text fields
var date = document.getElementById("Transaction_Date");
var amount = document.getElementById("Transaction_Amount");
// This is the transaction list
var transList = document.getElementById("CustomerTransactions");
var container = document.getElementById("TransactionResult");
// Date validation
$(date).change(function () {
if ($(this).val() !== "" && $(amount).val() !== "") {
$(save).prop('disabled', false);
} else {
$(save).prop('disabled', true);
}
});
// Amount validation
$(amount).keyup(function () {
if ($(this).val() !== "" && $(date).val() !== "") {
$(save).prop('disabled', false);
} else {
$(save).prop('disabled', true);
}
});
$('.submit').click(function(){
if($('form').valid()) {
$.ajax({
url: '@Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
data: {Answer: '', Question: $('#Question').val()},
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resp) {
openAlert(resp);
}});
}
else {
closeAlert();
}
});
});
</script>
</body>
</html>
我还想将动态列表添加到视图中,但不确定如何实现它。查看下面的dotnetfiddle链接以获取代码。
<div class="form-group">
Current transactions
<!-- Added here dynamically foreach transaction in transactions-->
Transactions:
<ul>
<li>TransactionDate: Date here</li>
<li>TransactionAmount: Amount here</li>
</ul>
</div>
<div class="form-group">
Current transactions
<!-- Added here dynamically-->
Transactions:
<ul>
<li>TransactionDate: Date here</li>
<li>TransactionAmount: Amount here</li>
</ul>
</div>
代码链接: https://dotnetfiddle.net/2uG3sv
你可以按如下方式使用 JQuery:
1-单击add
呼叫AddTransactionItem
时,使用$.port
。
2-如果没有错误,请隐藏模型。
$('#AddTransaction').click(function () {
var TransactionDate = $('#Transaction_Date').val();
var TransactionAmount = $('#Transaction_Amount').val();
$.post('@Url.Action("AddTransactionItem","Home")', { CustomerTransaction: {TransactionDate: TransactionDate, TransactionAmount: TransactionAmount} })
.done(function (data) {
$(".TransactionModal").modal('hide');
}).fail(
function (jqXHR, textStatus, errorThrown) {
alert("create", jqXHR.responseText, 'error');
});
});
3-对于返回数据,您可以轻松返回JSON消息,例如:
[HttpPost]
public IActionResult AddTransactionItem(SampleViewModel model)
{
model.CustomerTransactions = new List<SampleTransactionItemViewModel> {model.CustomerTransaction};
// model.CustomerTransaction = null;
return Json("any message here");
//return PartialView("Modal/TransactionModal", output);
// return View("FraudCheckBankAccountForm", model);
}