1

I know this question has been asked a lot and I have tried every solution I can find but I still cannot get my Ajax form to update the DIV rather then redirecting to the Action Method e.g(Local..Home/Index_AddUser). I have shortened the code as it is very long otherwise:

View

@using (Ajax.BeginForm("Index_AddUser", new AjaxOptions{UpdateTargetId = "userList"}))
    {
        @Html.AntiForgeryToken()
        //This summarises user input and displays error messages
        @Html.ValidationSummary()

        <div id="aParent">

            <div align="justify">
                <div>@Html.LabelFor(model => model.UserLogin)</div>
                <div>@Html.EditorFor(model => model.UserLogin, new { id = "UserLogin" })</div>
            </div>
            //Same as above repeated with different values
            <div>
                <div><input type="submit" value="Add User" id="UserCreate" /></div>
            </div>
        </div>
    }

<div id="userList">
    @{Html.RenderAction("UserListControl");}
</div>

Partial View

@model IEnumerable<WebApplication1.Models.UserDetail>
            <table>
            <!-- Render the table headers. -->
            <thead>
                <tr>
                    //Table Headers matching LabelFor in VIew
                </tr>
            </thead>
                <tbody>
                    @foreach (var item in Model)
                    {
                        <tr>
                            //Table Rows from db
                        </tr>
                    }
                </tbody>
        </table>

UserDetailsController

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index_AddUser([Bind(Prefix = "NewUserDetails")]UserDetail model)
    {
        Manager manager = new Manager();
            if (model != null)
            {
                manager.SaveUser(model.UserID, model.UserLogin, model.FirstName, model.Surname, model.Email, model.Active);
                return PartialView("UserListControl");
            }
            return PartialView("UserListControl");
        }

_Layout

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jqueryui")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

Web.config

  <appSettings>
    <add key="webpages:Version" value="3.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>

BundleConfig

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));

Thanks in advance and I am new to Stack and MVC so if you need any more information please ask :)

hjardine
  • 495
  • 3
  • 17
  • generally it redirects if you have not used `@Ajax.BeginForm`s proper overload, or you have not added all the scripts. Try using one form with controller name too, also check network tab of developer tool if you have added all the required scripts and its loading, add httpmethod and insertionmode to ajax options – Chaitanya Gadkari Jul 22 '15 at 07:01
  • @ChaitanyaGadkari I did this: `@using (Ajax.BeginForm("Index_AddUser", new AjaxOptions{HttpMethod = "POST", UpdateTargetId = "userList", InsertionMode = InsertionMode.Replace}))` – hjardine Jul 22 '15 at 07:08
  • @ChaitanyaGadkari It still is redirecting to a new page – hjardine Jul 22 '15 at 07:08
  • checked other things? like if all the scripts are loading, and tried with beginform with controller name in it? also see if http://stackoverflow.com/questions/15253692/mvc-4-ajax-beginform-submit-causes-full-postback helps – Chaitanya Gadkari Jul 22 '15 at 07:13

1 Answers1

1

Why not try Javascript with jquery to update the div async? instead of using mvc controls?

in my opinion I would display the user using the View and Use a partial view to Add a new user.

This would mean your view Users

<input type="button" id="addUser" onclick="newUser()" value="Add User"/>
<div id="NewUserDiv"></div>
@model IEnumerable<WebApplication1.Models.UserDetail>
        <table>
        <!-- Render the table headers. -->
        <thead>
            <tr>
                //Table Headers matching LabelFor in VIew
            </tr>
        </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        //Table Rows from db
                    </tr>
                }
            </tbody>
    </table>

Your javascript for this page

        function newUser() {
        $.ajax({
            url: '/Home/CreateUser',
            success: function (data) {
                $('#NewUserDiv').html(data);
            }
        });
    }

Your partial Add user View CreateUser

  @using (Html.BeginForm("CreateUser", "Home", FormMethod.Post, new { encType = "multipart/form-data", name = "NewEmployeeForm", @class = "form-group" }))
        {
            @Html.AntiForgeryToken()
    //This summarises user input and displays error messages
    @Html.ValidationSummary()

    <div id="aParent">

        <div align="justify">
            <div>@Html.LabelFor(model => model.UserLogin)</div>
            <div>@Html.EditorFor(model => model.UserLogin, new { id = "UserLogin" })</div>
        </div>
        //Same as above repeated with different values
        <div>
            <div><input type="submit" value="Add User" id="UserCreate" /></div>
        </div>
    </div>
        }

Controller method in Home for your add User partial View

    [HttpGet]
    public ActionResult CreateUser()
    {
        var user = new UserDetail();
        return PartialView("CreateUser", user);
    }

    [HttpPost]
    public ActionResult CreateUser(UserDetail model)
    {
    Manager manager = new Manager();
        if (model != null)
        {
            manager.SaveUser(model.UserID, model.UserLogin, model.FirstName, model.Surname, model.Email, model.Active);
        }
        return RedirectToAction("Home", "Users");
    }
WhaChi
  • 56
  • 1
  • 8
  • If you could provide a sample it would be much appreciated – hjardine Jul 22 '15 at 06:48
  • this is not an answer. I know you cant comment due to reputation, but you could add code if you know how to do it to help the OP – Chaitanya Gadkari Jul 22 '15 at 06:51
  • From your code you want to add a user and display all of the users. am I correct? – WhaChi Jul 22 '15 at 06:59
  • Yes so i get the display of the users (a table) from the Partial view which is working fine and when they click submit in the view i want this new user to be added to the table without the full page reloading – hjardine Jul 22 '15 at 07:06
  • I would do it the other way around (such as @WhaChi answered). this way you you have the "Add User" as a Partial view, this can also be altered that you only add the new Item to the table without refreshing the whole page, however the way this is done is a good way, I am also using this approach is it is working quite well. – Donald Jansen Jul 22 '15 at 07:23
  • I have followed these steps but on Button Click nothing is happening @WhaChi – hjardine Jul 22 '15 at 07:51
  • Sorry Typo – WhaChi Jul 22 '15 at 07:56
  • Still nothing happening? – hjardine Jul 22 '15 at 08:02
  • Do you get any javascript errors when you click on the button ? (right click inspect element) – Donald Jansen Jul 22 '15 at 08:05
  • Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/. – hjardine Jul 22 '15 at 08:15
  • Ah it is working now, i just recopied it, i must have changed something by accident. Thank you very much for your help, you get a big tick :) – hjardine Jul 22 '15 at 08:16