小编典典

如何在Asp.net MVC 4中使用Simple Ajax Beginform?[关闭]

ajax

我是Asp.netMVC的新手,我进行了研究,Ajax.BeginForm但是当我应用代码时,它不起作用。您可以Ajax.Beginform与View,Controller,Model共享非常简单的示例吗?谢谢。


阅读 246

收藏
2020-07-26

共1个答案

小编典典

简单示例:带有文本框和“搜索”按钮的表单。

如果您在“ textbox并提交”表格中填写“姓名” ,则会为您带来表中带有“姓名”的患者。

视图:

@using (Ajax.BeginForm("GetPatients", "Patient", new AjaxOptions {//GetPatients is name of method in PatientController
    InsertionMode = InsertionMode.Replace, //target element(#patientList) will be replaced
    UpdateTargetId = "patientList",
    LoadingElementId = "loader" // div with .gif loader - that is shown when data are loading   
}))
{
    string patient_Name = "";
    @Html.EditorFor(x=>patient_Name) //text box with name and id, that it will pass to controller
    <input  type="submit" value="Search" />
}

@* ... *@
<div id="loader" class=" aletr" style="display:none">
    Loading...<img src="~/Images/ajax-loader.gif" />
</div>
@Html.Partial("_patientList") @* this is view with patient table. Same view you will return from controller *@

_ PatientList.cshtml:

@model IEnumerable<YourApp.Models.Patient>

<table id="patientList" >
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Name)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Number)
    </th>       
</tr>
@foreach (var patient in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => patient.Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => patient.Number)
    </td>
</tr>
}
</table>

Patient.cs

public class Patient
{
   public string Name { get; set; }
   public int Number{ get; set; }
}

PatientController.cs

public PartialViewResult GetPatients(string patient_Name="")
{
   var patients = yourDBcontext.Patients.Where(x=>x.Name.Contains(patient_Name))
   return PartialView("_patientList", patients);
}

而且,正如TSmith在评论中所说,不要忘记通过NuGet安装
jQuery Unobtrusive Ajax
库。

2020-07-26