C# 如何在html中调用我的方法?
我想在mvc视图中调用我的方法。我有一个名为SavePersoon的方法,它必须将更改的数据保存到我的数据库中。这是我的服务代码:C# 如何在html中调用我的方法?,c#,html,asp.net,asp.net-mvc,wcf,C#,Html,Asp.net,Asp.net Mvc,Wcf,我想在mvc视图中调用我的方法。我有一个名为SavePersoon的方法,它必须将更改的数据保存到我的数据库中。这是我的服务代码: public bool SavePersoon(PersoonModel persoon) { bool result = true; db.Persoon.AddOrUpdate(persoon.GetPoco()); db.SaveChanges(); return result;
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>
opslan
我必须使用类似的东西吗,比如
你可以使用Ajax,类似这样的东西
$("#btnSaveChanges").on("click",function(){
$.ajax({
url:"/controllerName/SavePersoon",
data:$("#formName").serialize(),
cache:false,
type:"POST",
error:function(){
alert("Error");
}
});
});
如果您使用Razor view engaine,您可以让您的方法返回操作结果,并使用Html.Actionlink从视图中调用它。您可以做两件事:
使用ASP.Net MVC提供的HTML帮助程序创建一个表单,该表单将发布到所需的方法,类似于控制器“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>
}
你的问题不清楚。请更好地解释这个场景。展示你的观点。你有表格吗?您需要type=“submit”
在如下JavaScript部分提交表单:$(“#btnSaveChanges”)。在(“click”,function(){//Your code}上,我必须补充一点,我在JavaScript中使用JQuery。我已经更新了第一部分,因为它需要一个HTML提交控件,将表单内容提交到操作url。
$("#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");
}
});
});