简体   繁体   中英

How to pass model between different method of controller from view MVC

I search much but I am not lucky to find the solution, My aim is save a model depending on the button that the user chooses.

I have two inputs of type button, which should each invoke a different method from the controller at the moment of press click. You must have an account. All this happens in the same view for only a model.

This is my view:

@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>
}

And these are my methods:

[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");
   }
}

In order that they are in context, I want to guard the model in the database and in memory with SQLite, and any suggestion is welcome.

I think you can use formaction attribute (HTML5) for this. Try the following. Hope to help, my friend :))

<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" />

Note: It just can be implemented in HTML5.

consider the following sample , how to send a model to different methods of same controller:

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)"' />

}

For a jQuery solution change your <input> elements into plain <button> ones and use the below jQuery in your $(document).ready() function :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM