[英]How to pass model between different method of controller from view MVC
我進行了很多搜索,但我並不幸運找到解決方案,我的目標是根據用戶選擇的按鈕保存模型。
我有兩個類型為button的輸入,在按下按鈕時,它們應該分別從控制器調用不同的方法。 您必須有一個帳戶。 所有這些僅在模型的同一視圖中發生。
這是我的看法:
@model WebShop.Models.Product
@{
ViewBag.Title = "Create";
}
<h2>Crear</h2>
@using Newtonsoft.Json
@using (Html.BeginForm(new { @id = "create" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Producto</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.ProductNumber, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ProductNumber, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ProductNumber, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ProductTitle, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ProductTitle, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ProductTitle, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Crear" class="btn btn-default" />
<input type="submit" value="Crear en memoria" class="btn btn-default" id="InMemory" />
</div>
</div>
</div>
}
這些是我的方法:
[HttpPost]
public ActionResult Create(Product product)
{
try
{
List<Product> listProducts = new List<Product>();
if (ModelState.IsValid)
{
db.Products.Add(product);
db.SaveChanges();
TempData["list"] = db.Products.ToList();
return RedirectToAction("Index");
}
return View(product);
}
catch
{
return View(product);
}
}
[HttpPost]
public ActionResult CreateInMemory(Product product)
{
try
{
if (ModelState.IsValid)
{
using (SQLiteConnection con = new SQLiteConnection("Data Source=:memory:"))
{
con.Open();
if (string.IsNullOrEmpty(result.ToString()))
{
string query = @"CREATE TABLE Products
(ProductID integer primary key,
ProductNumber integer,
ProductTitle varchar(100));";
using (SQLiteCommand comd = new SQLiteCommand(query,con))
{
comd.ExecuteNonQuery();
TempData["list"] = saveListProduct(product, con);
}
}
else
{
TempData["list"] = saveListProduct(product, con);
}
con.Close();
return RedirectToAction("Index");
}
}
return View(product);
}
catch(Exception e)
{
string message = e.Message;
return View("Index");
}
}
為了使它們處於上下文中,我想使用SQLite保護數據庫和內存中的模型,歡迎提出任何建議。
我認為您可以為此使用formaction屬性(HTML5)。 請嘗試以下方法。 希望對您有幫助,我的朋友:))
<input type="submit" name="response" value="Create" formaction=@Url.Action("Create") formmethod="post" class="btn btn-default" />
<input type="submit" name="response" value="CreateInMemory" formaction=@Url.Action("CreateInMemory") formmethod="post" class="btn btn-default" />
注意:只能在HTML5中實現。
考慮以下示例,如何將模型發送到同一控制器的不同方法:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Method1(BooModel model)
{
...
}
[HttpPost]
public ActionResult Method2(BooModel model)
{
...
}
}
public class BooModel
{
public int Id { get; set; }
public string Name { get; set; }
}
@model WebApi.Controllers.BooModel
@using (Html.BeginForm())
{
@Html.TextBoxFor(x=>x.Id)
@Html.TextBoxFor(x=>x.Name)
<input type="submit" value="Method1" onclick='this.form.action="@Url.Action("Method1", "Home", null, this.Request.Url.Scheme)"' />
<input type="submit" value="Method2" onclick='this.form.action="@Url.Action("Method2", "Home", null, this.Request.Url.Scheme)"' />
}
對於jQuery解決方案,請將您的<input>
元素更改為普通的<button>
<input>
元素,並在$(document).ready()
函數中使用以下jQuery:
$("#btnCreate").on('click', function () {
$.ajax({
url: '@Url.Action("Create", "Controller", new { area="Area"})',
type: "POST",
data: $('form').serialize(),
success: function () {
//Go to new location etc
}
})
})
$("#btnCreateInMemory").on('click', function () {
$.ajax({
url: '@Url.Action("CreateInMemory", "Controller", new { area="Area"})',
type: "POST",
data: $('form').serialize(),
success: function () {
//Go to new location etc
}
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.