开发者

Ajax.BeginForm Not Doing What It's Supposed To Do?

开发者 https://www.devze.com 2023-03-17 15:52 出处:网络
I have a dialog box in which there are tabs. In one of the tabs, the addresses entered by the user are displayed. There\'s also a button which allows the user to add a new address. When the user click

I have a dialog box in which there are tabs. In one of the tabs, the addresses entered by the user are displayed. There's also a button which allows the user to add a new address. When the user clicks on the button, the contents of the current tab are replaced with the "Add" view.

What I'm trying to accomplish here is to allow the user to add the address, and once they click ok, the form should be submitted via an AJAX call, and then the tab should be updated with the contents of the "Index" view (which displays the user's addresses).

Unfortunately, that's not working properly. Rather than submitting the form via an AJAX call, it's doing a regular post action and displaying the Index view on a white background instead of displaying it in the tab.

Here's my code:

    [HttpPost]
    public ActionResult Add(AddressDto model)
    {
        if(!ModelState.IsValid)
        {
            return PartialView(model);
        }
        Area area = null;
        if(!string.IsNullOrEmpty(model.Area))
        {
            area = _addressService.GetAreaByName(model.Area);
        }
        var newAdd = new Address
                         {
                             Details = model.Details,
                             Name = model.Name,
                             IsDefaultAddress = false,
                             CountryName = _addressService.GetCountryById(int.Parse(model.Country)).Name,
                             User = _helper.GetUserFromSession(HttpContext.User.Identity.Name)
                         };
        if(area != null)
            area.Addresses.Add(newAdd);
        else 
            _addressService.Create(newAdd);
        _unitOfWork.Commit();
        var indexViewModel = PrepareIndexView();
        return PartialView("Index", indexViewModel);
    }

    private UserLocationViewModel PrepareIndexView()
    {
        var nickname = this.HttpContext.User.Identity.Name;
        var user = _helper.GetUserFromSession(nickname, true);
        var viewModel = Mapper.Map<User, UserLocationViewModel>(user);
        return viewModel;
    }

And here's how I'm starting the form:

@using (Ajax.BeginForm("Add", "Address", new AjaxOptions { UpdateTargetId = "ui-tabs-2", InsertionMode = InsertionMode.Replace, HttpMethod = "POST"开发者_开发问答 }))

So what's wrong with my setup?


Make sure you have included the following script to your page:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号