【问题标题】:How to call method on the Controller from view如何从视图中调用控制器上的方法
【发布时间】:2021-09-12 04:03:08
【问题描述】:

首先,我对此有点陌生,我有很多问题,但其中一个是下一个问题。 有没有办法从另一个视图调用位于控制器上的方法(没有视图)并同时发送一个参数? 我一直在努力,但我做不到。 我试过这个:

@{
  ((HomeController)this.ViewContext.Controller).Method1();
}

但我收到一个错误,提示找不到命名空间 流程是:打开视图->单击添加按钮->从其他表中选择一行->通过编码,将产品的ID发送到我需要的方法以查找产品并将其插入到我的新表中.

这里有一些代码。

第一次查看

<div id="lista" class="modal fade" role="dialog">
    <div class="modal-dialog">


        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">

                @{Html.RenderAction("selectOrden", "Producto");}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
            </div>
        </div>

    </div>
</div>

控制器

    [HttpGet]
        public ActionResult selectOrden()
        {
            try
            {
                client = new FireSharp.FirebaseClient(config);
                FirebaseResponse response = client.Get("Producto");
                dynamic data = JsonConvert.DeserializeObject<dynamic>(response.Body);
                var list = new List<Producto>();
                foreach (var item in data)
                {
                    list.Add(JsonConvert.DeserializeObject<Producto>(((JProperty)item).Value.ToString()));
                    Debug.WriteLine(JsonConvert.DeserializeObject<Producto>(((JProperty)item).Value.ToString()).nombreProducto);
                    return View(list);
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
            }
            return View();
        }

        //Inserta registros de productos en las ordenes de compra

        [HttpPost]
        public void selectOrdena(string id)
        {
            client = new FireSharp.FirebaseClient(config);
            FirebaseResponse responseProdu = client.Get("Producto/" + id);
            Producto dataProdu = JsonConvert.DeserializeObject<Producto>(responseProdu.Body);
            ViewBag.Soli = dataProdu;


            Debug.WriteLine("Hello");

            //return View(dataProdu);
        }

第二次查看

    @model IEnumerable<FirebaseMVCTestApp.Models.Producto>
    
    @{
        ViewBag.Title = "selectOrden";
        Layout = null;
    }
    
    <h2>selectOrden</h2>
    
    @using (Html.BeginForm("Save","ProductoController", FormMethod.Post))
    {
    
        <form method="post">
            @Html.AntiForgeryToken()
    
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <table id="table_idxd" class="display">
                <thead>
                    <tr>
                        <th>
                            Nombre del producto
                        </th>
                        <th>
                            Cantidad
                        </th>
                        <th>
                            Costo
                        </th>
                        <th>
                            Precio
                        </th>
                        <th>
                            Codigo
                        </th>
                        <th>Acción</th>
                    </tr>
                </thead>
                @{ try
                    {
                        foreach (var item in Model)
                        {
                            <tr>
    
                                <td>
    
                                    @Html.EditorFor(model => item.nombreProducto, new { htmlAttributes = new { @class = "form-control" } })
    
                                </td>
                                <td>
                                    @Html.EditorFor(modelItem => item.cantidad, new { htmlAttributes = new { @class = "form-control" } })
    
                                </td>
                                <td>
                                    @Html.EditorFor(modelItem => item.costo, new { htmlAttributes = new { @class = "form-control" } })
    
                                </td>
                                <td>
                                    @Html.EditorFor(modelItem => item.precio, new { htmlAttributes = new { @class = "form-control" } })
    
                                </td>
                                <td>
                                    @Html.EditorFor(modelItem => item.codigo, new { htmlAttributes = new { @class = "form-control" } })
    
                                </td>
                                <td>
                                    @Html.ActionLink("Agregar", "selectOrdena", new { id = item.idProducto })
                                    <input type="submit" value="Save" class="btn btn-default" />
                                   
                                </td>
                            </tr>
                        }
                    }
                    catch (Exception ex)
                    {
    
                    }
    
    
                }
            </table>
        </form>
    
    
    
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
    
            </div>
        </div>
    
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

【问题讨论】:

  • 是的,可以在没有视图的情况下调用控制器方法,但下一个问题是执行该方法后需要发生什么?
  • 您应该记住,您只能在服务器端从视图调用任何方法。因此,如果您从控制器调用方法并将结果传递给视图,这将是相同的。但在这种情况下,代码将更具可维护性和可读性。

标签: asp.net asp.net-mvc asp.net-core asp.net-web-api


【解决方案1】:

您提供的方法有效。 这是您在 Controller 上调用实例方法的方式:

@{
  ((HomeController)this.ViewContext.Controller).Method1();
}

这是在任何类中调用静态方法的方式:

@{
    SomeClass.Method();
}

假设该方法是公共的并且对视图可见,这将起作用。但是根据您所说的,报告了错误:

找不到该命名空间

原因可能是引用程序集的项目可能与程序集的框架类型不同。您可以查看此帖子,它可能对您有所帮助:https://stackoverflow.com/questions/4764978/the -type-or-namespace-name-could-not-be-found

【讨论】:

    【解决方案2】:

    好的,我检查了所有其他线程,我认为它与我的问题相去甚远,但我已经通过在第二个视图中添加这一行来解决它

    @using FirebaseMVCTestApp.Controllers
    

    这样视图可以看到我需要的控制器。

    我知道这个问题是个小菜鸟,但如果我不问,我可能永远找不到答案。

    谢谢。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-26
      • 2013-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多