开发者

Post MVC view data with jQuery

开发者 https://www.devze.com 2023-02-13 05:23 出处:网络
HI, I am sending Product Model to my controller meth开发者_开发知识库od. i am getting string for posted form. it need to send it in key/value pair or whole product model. Any help would be apprecaited

HI, I am sending Product Model to my controller meth开发者_开发知识库od. i am getting string for posted form. it need to send it in key/value pair or whole product model. Any help would be apprecaited.

 var link = '/Product/AddRec?callback=?';

 var formdata = $("form").serialize(); 
               $.ajax({
                   url: link,
                   type: 'POST',
                   data: { 
                        'obj' : formdata,
                       'jin': 1,
                       'deb': 2)
                   },
                   dataType: "jsonp"

               });


I think it should work

$.ajax({
    url: '/Product/AddRec?callback=?',
    type: 'POST',
    data: $("form").serialize() + "&jin=1&deb=2"
});

edit:

as Darin Dimitrov requested, here go my humble explanation

Consider my Product class

public class Product {
    public int Id { get; set; }
    public string Name { get; set; }
}

I suppose your action is something like

[HttpPost]
public ActionResult AddRec(Product product, int jin, int deb) {
    // code
}

The form

<form id="productForm">
    <%: Html.HiddenFor(p => p.Id) %>
    <%: Html.TextBoxFor(p => p.Name) %>
    <input type="button" value="Send form" onclick="SendForm();" />
</form>

Suppose that Id = "1" and Name = "Darin Dimitrov".

jQuery will serialize my form like this

Id=1&Name=Darin+Dimitrov

and will concat with the extra data to become

Id=1&Name=Darin+Dimitrov&jin=1&deb=2

<script type="javascript/text">
    function SendForm() {
        $.ajax({
            url: '/Product/AddRec?callback=?',
            type: 'POST',
            data: $("#productForm").serialize() + "&jin=1&deb=2"
        });
    }
</script>

the action should receive

product.Id = 1
product.Name = "Darin Dimitrov"
jin = 1
deb = 2

that's all, sorry If I can't help you OP.


I would use the jQuery form plugin to do this. It handles serializing the form contents and, if you look at the options, you can specify additional data. Your example above would become:

$.ajaxSubmit({
                   url: link,
                   type: 'POST',
                   data: { 
                       'jin': 1,
                       'deb': 2)
                   },
                   dataType: "jsonp"

               });

It takes care of serializing the form and sending the data to the server in the appropriate form.

0

精彩评论

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