Submit form using AJAX in Asp.Net mvc 4

后端 未结 1 453
陌清茗
陌清茗 2020-11-30 22:35

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 figu

相关标签:
1条回答
  • 2020-11-30 23:08

    Here goes the complete example -

    Lets create a simple model -

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

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

    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 -

    enter image description here

    Now when you enter data and click on create button -

    enter image description here

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

    enter image description here

    0 讨论(0)
提交回复
热议问题