我想在视图中单击按钮时调用控制器。如何在MVC中执行此操作?。
这是我的第一个控制人员。
public ActionResult DetailForm()
{
graduandModel model = new graduandModel();
var ceremonyList = _ceremonyService.GetAllCeremonyByDate(DateTime.Now);
if (ceremonyList.Count == 0)
{
return Content("No ceremony can be loaded");
}
else
{
foreach (var c in ceremonyList)
{
model.AvailableCeremony.Add(new SelectListItem() {
Text = "Ceremony at " + c.ceremony_date.ToString(),
Value = c.ceremony_id.ToString() });
}
return View(model);
}
}
这是我的观点。
@{
Layout = "~/Views/Shared/_ColumnsThree.cshtml";
}
@model graduandModel
@using Nop.Web.Models.Hire;
@using Nop.Web.Framework;
@using Telerik.Web.Mvc.UI;
@using System.Linq;
<table>
<tr>
<td>
@Html.LabelFor(model => model.ceremony_id)
</td>
<td>
@Html.DropDownListFor(model => model.ceremony_id, Model.AvailableCeremony)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.first_name):
</td>
<td>
@Html.EditorFor(model => model.first_name)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.middle_name):
</td>
<td>
@Html.EditorFor(model => model.middle_name)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.last_name):
</td>
<td >
@Html.EditorFor(model => model.last_name)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.student_id):
</td>
<td>
@Html.EditorFor(model => model.student_id)
</td>
</tr>
<tr>
<td colspan="2" class="buttons">
<input type="submit" id="btnsearchgraduand" name="btnsearch"
class="searchbutton" value="@T("Search")" />
</td>
</tr>
</table>
然后当我点击搜索按钮时,我想检查输入数据。 我应该写这样的新控制器
public ActionResult CheckDegreeDetails()
{
graduandModel model = new graduandModel();
var degreeList = _graduandService.GetGraduandByStudent(
model.ceremony_id, model.first_name,
model.middle_name, model.last_name);
return View(model);
}
或者...
我不知道如何在点击按钮时调用控制器......
答案 0 :(得分:3)
您希望在表单中包装用户输入字段和提交按钮。您可以使用html帮助程序,它也可以指定要调用的控制器操作。 所以修改你的观点:
...
@model graduandModel
@using Nop.Web.Models.Hire;
@using Nop.Web.Framework;
@using Telerik.Web.Mvc.UI;
@using System.Linq;
@using(Html.BeginForm("DetailForm", "ControllerName", FormMethod.Post, new {enctype="multipart/form-data"})
{
<table >
<tr>
<td >
@Html.LabelFor(model => model.ceremony_id)
</td>
...
//code omitted for brevity
...
<input type="submit" id="btnsearchgraduand" name="btnsearch" class="searchbutton" value="@T("Search")" />
})
然后在您的控制器中,您需要添加方法以“捕获”此表单。您已经在使用强类型视图,因此很容易捕获数据
[HttpPost]
public ActionResult DetailForm (graduandModel model)
{
//do what you need to do with the data here
//the model passed into this method's parameter should
//contain all the data from the editor templates in the view
}
答案 1 :(得分:1)
按钮的方式,它不会发出请求。
您可以使用jQuery / javascript。 HTML:
使用Javascript:
function callController()
{
$.get("YourController/Action",data, callBackMethod);
}
或者您可以使用@using(Html.BeginForm(..))
包装输入,按钮等