C# 如何从MVC视图在不同的控制器方法之间传递模型

C# 如何从MVC视图在不同的控制器方法之间传递模型,c#,asp.net-mvc,C#,Asp.net Mvc,我搜索了很多,但我没有幸运地找到解决方案,我的目标是根据用户选择的按钮保存一个模型 我有两个类型为button的输入,每个输入都应该在按下click时从控制器调用不同的方法。你必须有一个帐户。所有这些仅在模型的同一视图中发生 我的看法是: @model WebShop.Models.Product @{ ViewBag.Title = "Create"; } <h2>Crear</h2> @using Newtonsoft.Json @using (Ht

我搜索了很多,但我没有幸运地找到解决方案,我的目标是根据用户选择的按钮保存一个模型

我有两个类型为button的输入,每个输入都应该在按下click时从控制器调用不同的方法。你必须有一个帐户。所有这些仅在模型的同一视图中发生

我的看法是:

@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>
}
@model WebShop.Models.Product
@{
ViewBag.Title=“创建”;
}
克雷尔
@使用Newtonsoft.Json
@使用(Html.BeginForm(new{@id=“create”}))
{
@Html.AntiForgeryToken()
产品

@Html.ValidationSummary(true,“,new{@class=“text danger”}) @LabelFor(model=>model.ProductNumber,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.ProductNumber,new{htmlAttributes=new{@class=“form control”}}) @Html.ValidationMessageFor(model=>model.ProductNumber,“,new{@class=“text danger”}) @LabelFor(model=>model.ProductTitle,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.ProductTitle,new{htmlAttributes=new{@class=“form control”}}) @Html.ValidationMessageFor(model=>model.ProductTitle,“,new{@class=“text danger”}) }
以下是我的方法:

[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");
   }
}
[HttpPost]
公共行动结果创建(产品)
{
尝试
{                            
列表产品=新列表();
if(ModelState.IsValid)
{                    
db.Products.Add(产品);
db.SaveChanges();
TempData[“list”]=db.Products.ToList();
返回操作(“索引”);
}               
返回视图(产品);
}
抓住
{                
返回视图(产品);
}
}
[HttpPost]
公共操作结果CreateInMemory(产品)
{
尝试
{        
if(ModelState.IsValid)
{
使用(SQLiteConnection con=newsqliteconnection(“数据源=:内存:))
{                          
con.Open();
if(string.IsNullOrEmpty(result.ToString()))
{
字符串查询=@“创建表产品”
(ProductID整数主键,
ProductNumber整数,
ProductTitle varchar(100));“;
使用(SQLiteCommand-comd=newsqlitecommand(query,con))
{                               
comd.ExecuteOnQuery();
TempData[“列表”]=保存列表产品(产品,con);
}
}
其他的
{
TempData[“列表”]=保存列表产品(产品,con);
}
con.Close();
返回操作(“索引”);
}
}                      
返回视图(产品);
}
捕获(例外e)
{
字符串消息=e.消息;
返回视图(“索引”);
}
}

为了使它们处于上下文中,我想用SQLite保护数据库和内存中的模型,欢迎任何建议。

对于jQuery解决方案,请将
元素更改为普通
元素,并在
$(文档)中使用以下jQuery。ready()
函数:

$("#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
        }
    })
})

我认为您可以使用formaction属性(HTML5)来实现这一点。尝试以下方法。希望能帮上忙,我的朋友:))



注意:它只能在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)"' />

}
公共类HomeController:控制器
{
公共行动结果索引()
{
返回视图();
}
[HttpPost]
公共行动结果方法1(BooModel模型)
{
...
}
[HttpPost]
公共行动结果方法2(BooModel模型)
{
...
}
}
公共类BooModel
{
公共int Id{get;set;}
公共字符串名称{get;set;}
}
@模型WebApi.Controllers.BooModel
@使用(Html.BeginForm())
{
@Html.TextBoxFor(x=>x.Id)
@Html.TextBoxFor(x=>x.Name)
}

据我所知,您有两个按钮。一个用于保存到DB中,一个用于使用SQLite保存到内存中,对吗?单击按钮时需要更改表单操作,类似于onclick='this.form.action=“somethingelse”;正确,就像@tomato32一样,您是在寻找纯MVC解决方案还是接受jquery解决方案?欢迎@Wurd提供任何解决方案
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)"' />

}