在 Asp.Net mvc 4 中使用 AJAX 提交表单

IT技术 javascript jquery asp.net ajax asp.net-mvc
2021-03-13 15:03:32

我正在尝试学习asp.net,到目前为止我可以加载其他页面内容而无需刷新使用Ajax.ActionlinkAjaxOptions()但我无法弄清楚在提交表单时如何使用ajax。我做了很多谷歌搜索,但找不到合适的解决方案。这是我的代码,

控制器页面

namespace CrudMvc.Controllers
{
public class HomeController : Controller
{
    sampleDBEntities db = new sampleDBEntities(); 
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View(db.myTables.ToList());
    }

    public PartialViewResult Details(int id = 0)
    {
        myTable Table = db.myTables.Find(id);
        return PartialView(Table);
    }

    [HttpGet]
    public PartialViewResult Create()
    {
        return PartialView();
    }

    [HttpPost]
    public ActionResult Create(myTable table)
    {
        if (ModelState.IsValid)
        {
            db.myTables.Add(table);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(table);
    }

    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }
}
}

Index 查看页面

@model IEnumerable<CrudMvc.Models.myTable>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

<h2>Index</h2>

<p>
@Ajax.ActionLink("Add New", "Create", new AjaxOptions()
   {
    HttpMethod = "GET",
    UpdateTargetId = "info",
    InsertionMode = InsertionMode.Replace   
   })
</p>
<div id="main">
<table>
<tr>
    <th>
        @Html.DisplayNameFor(model => model.name)
    </th>
    <th>Action</th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.name)
    </td>
    <td>
        @Ajax.ActionLink("Details", "Details", new{ id=item.id}, new AjaxOptions()
   {
    HttpMethod = "GET",
    UpdateTargetId = "info",
    InsertionMode = InsertionMode.Replace   
   })
    </td>
</tr>
}
</table>
</div>
<div id="info"></div>

Create 查看页面

@model CrudMvc.Models.myTable

@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
    <legend>myTable</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.id)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.id)
        @Html.ValidationMessageFor(model => model.id)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.name)
        @Html.ValidationMessageFor(model => model.name)
    </div>
    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

<script>
var form = $('#main');
$.ajax({
    cache: false,
    async: true,
    type: "POST",
    url: form.attr('action'),
    data: form.serialize(),
    success: function (data) {
        alert(data);
    }
});
</script>

<div>
@Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
1个回答

这是完整的例子 -

让我们创建一个简单的模型 -

public class Details
{
    public string Name { get; set; }
    public string Email { get; set; }
}

现在让我们创建几个动作来使用AJAX BEGINFORM-

    static List<Details> details = new List<Details>(); 
    public ActionResult GetMe()
    {
        return View();
    }

    public ActionResult SaveData(Details d)
    {
        details.Add(d);
        return Json(details.Count, JsonRequestBehavior.AllowGet);
    }

然后让我们创建一个简单的视图来承载 Ajax.BeginForm() -

@model RamiSamples.Controllers.Details

@{
    ViewBag.Title = "Ajax";
}

<h2>Ajax</h2>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

@using (Ajax.BeginForm("SaveData", new AjaxOptions()
{
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "dane"
}))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Details</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div id="dane">
    Number of Details : 
</div>

现在当页面被渲染时 -

在此处输入图片说明

现在,当您输入数据并单击创建按钮时 -

在此处输入图片说明

然后页面将自动更新添加的数量,如下所示 -

在此处输入图片说明

@ramiramilu 您能否通过为您的答案添加更新来举例说明?
2021-05-01 15:03:32
@Christof 您可以使用 AJAX 上传文件,我曾经想到的一种方法TempData是返回 aPartialView并更新目标 div。
2021-05-04 15:03:32
@ramiramilu 感谢这个很好的例子。我已经设法应用了这种方法,但遇到了两个问题:1)我曾经TempData["message"]从控制器返回到视图。其实好像填满了又回到了View,却看不到。是否可以使用TempData["message"]这种方法?2)我无法IEnumerable<HttpPostedFileBase> files使用这种方法将上传的文件传递给控制器。如何解决这个问题?
2021-05-07 15:03:32
@Christof 为了保护答案的完整性,我建议发布一个包含具体细节的新问题。
2021-05-18 15:03:32
嗨,我让它工作了 - 那是因为我需要各种参考 - 不知道为什么......这是我最终得到的工作...... bundles.Add(new ScriptBundle(“~/bundles/jquery”)。 Include("~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery.validate*", "~/Scripts/jquery.unobtrusive*"));
2021-05-21 15:03:32