Я много ищу, но мне не повезло найти решение. Моя цель - сохранить модель в зависимости от кнопки, которую выбрал пользователь.
У меня есть два входа типа кнопки, каждый из которых должен вызывать другой метод из контроллера в момент нажатия кнопки. Вы должны иметь учетную запись. Все это происходит в одном представлении только для модели.
Это мой взгляд:
@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, и любые предложения приветствуются.