【问题标题】:How do I call my method in html?如何在 html 中调用我的方法?
【发布时间】:2016-04-18 10:10:22
【问题描述】:

我想在我的 mvc 视图中调用我的方法。我有一个名为 SavePersoon 的方法,它必须将更改的数据保存到我的数据库中。这是我的服务代码:

public bool SavePersoon(PersoonModel persoon)
    {
        bool result = true;


        db.Persoon.AddOrUpdate(persoon.GetPoco());


        db.SaveChanges();
        return result;
    }

这是必须按下的按钮,然后上面的代码必须自己处理工作。

观点:

<button type="button" id="btnSaveChanges" class="btn btn-primary">Opslaan</button>

我必须使用类似&lt;asp:LinkButton... 的东西吗?

【问题讨论】:

  • 你的问题不清楚。请更好地解释这个场景。
  • 展示你的观点。你有表格吗?并且您需要type="submit" 提交表单

标签: c# html asp.net asp.net-mvc wcf


【解决方案1】:

你可以使用 Ajax ,类似这样的东西

$("#btnSaveChanges").on("click",function(){
   $.ajax({
     url:"/controllerName/SavePersoon",
     data:$("#formName").serialize(),
     cache:false,
     type:"POST",
     error:function(){
        alert("Error");
     }
   });
});

【讨论】:

    【解决方案2】:

    如果您使用 Razor 视图引擎,您可以让您的方法返回一个操作结果并使用 Html.Actionlink 从视图中调用它。

    【讨论】:

      【解决方案3】:

      你可以做两件事:

      使用 ASP.Net MVC 提供的 HTML Helpers 创建一个表单,该表单发布到所需的方法,例如控制器“Person”的“Save”:

      @using (Html.BeginForm("Save", "Person", FormMethod.Post, new { @class = "form-horizontal" })) {
      <div>
           <!-- Your HTML, this could for example be a text field for the person its name -->
      
           @Html.TextBoxFor(Model => Model.Name, new { @class = "form-control" })
      
           <input type="submit" class="btn btn-primary" value="Save" />
      </div>
      }
      

      这将为您创建一个表单标签,例如&lt;form action="person/save" method="post"&gt; ... your HTML &amp; the submit button ... &lt;/form&gt;

      另一种方法是使用 Ajax 来防止页面刷新,如上述帖子所述。

      $("#btnSaveChanges").on("click",function(){
         $.ajax({
           url: '@Url.Action("Save", "Person")', // Again an MVC HTML Helper to create a URL
           data:$("#Name").val(), // Posts the value of a text field with ID "Name"
           cache:false,
           type:"POST",
           success: funcion(returnValue) {
                // Do something with the result.
           }
           error:function(){
              alert("Error");
           }
         });
      });
      

      【讨论】:

      • 在这样的 JavaScript 部分中:
      • 我已经更新了第一部分,因为它需要一个 HTML 提交控件,它将表单的内容提交到操作 url。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多