使用 jQuery post 传递 ViewModel?

发布于 2024-10-25 03:03:45 字数 2532 浏览 1 评论 0原文

我正在尝试在 MVC 应用程序中使用 jQuery 发表一篇文章,根据这里的 SO 答案: 可以使用 jQuery在 ASP.NET MVC 中将 ViewModel 发送到控制器?

区别在于我使用它来删除动态视图中的项目(不用介意我直接发布删除,这是通过授权关闭的站点,我将使用 jQuery 进行确认,我只是不希望用户必须转到新页面)。因此,我需要能够发送 id 和 ViewModel(ViewModel 在删除任何项目之前保存任何添加的项目)。总的来说,我对这个解决方案并不是特别满意,但此时我只需要让它发挥作用!

所以我试图弄清楚如何根据上面的SO帖子发送id和ViewModel,但我不知道如何使用命名参数获取ViewModel。这不起作用:

$(".delete").click(function () {
    $.ajax({
        type: "POST",
        url: deleteurl,
        data: ({id : $(this).closest('tr').find('td:first').text(),vm: $('form').serialize()}),
        cache: false,
        success: function (html) {
            $("#rows").html(html);
        }
    });
    return false;
});

这是 POST 操作方法:

        [HttpPost]
        public ActionResult Delete(int id, LanguageViewModel vm)
        {
            for (int i = 0; i < vm.Languages.Count; i++)
            {
                var language = _repository.GetLanguage(vm.Languages[i].Id); //This is the key, get the original program object to update
                UpdateModel(language, "Languages[" + i + "]");
            }
            _repository.Save();
//Delete code will go here
         return RedirectToAction("Edit", "Languages", new { id = id });
        //return View();
        }

同样,它不起作用,它甚至无法访问调试器中的操作方法。如果我从操作方法中删除 int id 参数,它实际上会到达那里,但 vm = null。我不知道该怎么做,所以任何帮助将不胜感激!

编辑: 抱歉,返回值现在应该是这样的,而不是 return View()。

更新:

在 Darin 的帮助下,它几乎可以工作了:

    [HttpPost]
    public ActionResult Delete(LanguageViewModel vm, FormCollection collection)
    {
        for (int i = 0; i < vm.Languages.Count; i++)
        {
            var language = _repository.GetLanguage(vm.Languages[i].Id); //This is the key, get the original program object to update
            UpdateModel(language, "Languages[" + i + "]");
        }
        _repository.Save(); 
        int id = Int32.Parse(collection["HiddenId"]);
        Language languageToDelete = _repository.GetLanguage(id);
        _repository.Delete(languageToDelete);
        vm.Languages.Remove(vm.Languages.SingleOrDefault(l => l.Id == id));
        _repository.Save();
        return PartialView("LanguageList", vm);
    }

但我已经更改为返回 PartialView (这是我从一开始就应该做的事情,因为这就是 jQuery 所做的 - 加载带有结果的 div)。但问题是,在从操作方法返回此部分视图并使用 jQuery 将其加载到 div 中后, $(".delete").click jQuery 函数不再工作......

有什么想法吗?

I'm trying to do a post with jQuery in an MVC application, according to this SO answer here:
Can jQuery do a POST of a ViewModel to a Controller in ASP.NET MVC?

The difference is I am using it to delete an item in a dynamic view (never mind the fact that I'm posting a delete directly, this is a closed site by authorization, and I will use jQuery to confirm, I just don't want the user to have to go to a new page). And I therefore need to be able to send both the id and the ViewModel (the ViewModel to save any added items before deleting any). I'm not particularly happy with the solution by and large, but at this point I just need to get it to work!

So I tried to figure out how to send both the id and the ViewModel according to the SO post above, but I can't figure out how to get the ViewModel in with the named parameters. This doesn't work:

$(".delete").click(function () {
    $.ajax({
        type: "POST",
        url: deleteurl,
        data: ({id : $(this).closest('tr').find('td:first').text(),vm: $('form').serialize()}),
        cache: false,
        success: function (html) {
            $("#rows").html(html);
        }
    });
    return false;
});

Here's the POST action method:

        [HttpPost]
        public ActionResult Delete(int id, LanguageViewModel vm)
        {
            for (int i = 0; i < vm.Languages.Count; i++)
            {
                var language = _repository.GetLanguage(vm.Languages[i].Id); //This is the key, get the original program object to update
                UpdateModel(language, "Languages[" + i + "]");
            }
            _repository.Save();
//Delete code will go here
         return RedirectToAction("Edit", "Languages", new { id = id });
        //return View();
        }

Again, it doesn't work, it doesn't even get to the action method in the debugger. If I remove the int id parameter from the action method it actually gets there, but with vm = null. I have no clue what to do, so any help will be greatly appreciated!

EDIT:
Sorry, the return value should be as changed now, not return View().

UPDATE:

With a little help from Darin it's almost working:

    [HttpPost]
    public ActionResult Delete(LanguageViewModel vm, FormCollection collection)
    {
        for (int i = 0; i < vm.Languages.Count; i++)
        {
            var language = _repository.GetLanguage(vm.Languages[i].Id); //This is the key, get the original program object to update
            UpdateModel(language, "Languages[" + i + "]");
        }
        _repository.Save(); 
        int id = Int32.Parse(collection["HiddenId"]);
        Language languageToDelete = _repository.GetLanguage(id);
        _repository.Delete(languageToDelete);
        vm.Languages.Remove(vm.Languages.SingleOrDefault(l => l.Id == id));
        _repository.Save();
        return PartialView("LanguageList", vm);
    }

But I have changed to return a PartialView (which was what I was supposed to do from the beginning since that is what the jQuery does - load a div with the results). But the problem is, after returning this Partial View from the action method and loading it in the div with jQuery, the $(".delete").click jQuery function doesn't work anymore...

Any ideas why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

去了角落 2024-11-01 03:03:45

您可以尝试在表单中包含一个隐藏字段,该字段将保存 id:

<input type="hidden" name="id" id="hiddenid" value="" />

,然后:

$('.delete').click(function () {
    var id = $(this).closest('tr').find('td:first').text();
    $('#hiddenid').val(id);
    $.ajax({
        type: 'POST',
        url: deleteurl,
        data: $('form').serialize(),
        cache: false,
        success: function (html) {
            $('#rows').html(html);
        }
    });
    return false;
});

可以简化为:

$('.delete').click(function () {
    var id = $(this).closest('tr').find('td:first').text();
    $('#hiddenid').val(id);
    $('#rows').load(deleteurl, $('form').serialize());
    return false;
});

You could try including a hidden field inside your form that will hold the id:

<input type="hidden" name="id" id="hiddenid" value="" />

and then:

$('.delete').click(function () {
    var id = $(this).closest('tr').find('td:first').text();
    $('#hiddenid').val(id);
    $.ajax({
        type: 'POST',
        url: deleteurl,
        data: $('form').serialize(),
        cache: false,
        success: function (html) {
            $('#rows').html(html);
        }
    });
    return false;
});

which could be simplified to:

$('.delete').click(function () {
    var id = $(this).closest('tr').find('td:first').text();
    $('#hiddenid').val(id);
    $('#rows').load(deleteurl, $('form').serialize());
    return false;
});
守不住的情 2024-11-01 03:03:45

您是否尝试过在发布之前将 id 附加到删除网址?

这样的事情对我有用:

deleturl = deleteurl + "/" + id;

hth,

\ ^ / ill

Have you tried appending the id to the deleteurl before posting?

Something like this has worked for me:

deleturl = deleteurl + "/" + id;

hth,

\ ^ / i l l

复古式 2024-11-01 03:03:45

将 FormCollection 作为第二个参数而不是 viewmodel 传递如何?然后,您可以在保存和/或删除之前对语言对象执行 TryUpdateModel。

How about passing the FormCollection as the second argument instead of viewmodel. Then you can do a TryUpdateModel on your language object before saving and/or deleting.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文