在Asp.Net MVC 4提交使用AJAX形式 [英] Submit form using AJAX in Asp.Net mvc 4

查看:141
本文介绍了在Asp.Net MVC 4提交使用AJAX形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学习asp.net,到目前为止,我可以加载其他页面内容,而无需使用刷新 Ajax.Actionlink AjaxOptions() ,但我无法弄清楚如何提交表单时,使用AJAX。我做了很多谷歌上搜索,但没有找到合适的解决方案。这里是我的codeS,

I'm trying to learn asp.net and so far I can load other page contents without refreshing using Ajax.Actionlink and AjaxOptions() but I can't figure it out how to use ajax when submitting a form. I did a lot of googling but couldn't find the appropriate solution. Here are my codes,

控制器页

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);
    }
}
}

首页查看网页

@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>

创建查看页面

@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")
}

我只需要AJAX的一个简单的锻炼,因为我是新的,想学asp.net MVC 4.任何人的帮助将是非常美联社preciable。 TNX。

I just need a simple workout of ajax since I'm new and want to learn asp.net mvc 4. Anyone's help would be really appreciable. Tnx.

推荐答案

下面那张完整的例子 -

Here goes the complete example -

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

Lets create a simple model -

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

现在,让我们创建几个动作的使用,使GET和POST请求 AJAX BEGINFORM -

Now lets create couple of Actions to make GET and POST requests using 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() -

Then lets create a simple view which will host 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>

现在,当页面被呈现 -

Now when the page gets rendered -

现在,当你输入数据,然后点击创建按钮 -

Now when you enter data and click on create button -

和随后的页面会自动更新相加次数如下 -

And then the page will automatically updated with the number of additions as shown below -

这篇关于在Asp.Net MVC 4提交使用AJAX形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆