开发者

How do I send the value of field_1 and field_2 to an MVC controller using jQuery

I asked this question before but my answers were not for MVC. I will try again. Sorry if my question is not good as English is not my native language.

I want to send the value of some fields:

field_1
field_2
Field_3 

To the server using Ajax.

Is there a way I can do it using jQuery? Note 开发者_JS百科that sometime it's fields 1-3 and sometime maybe more fields.


Sure, this is possible. What it sounds like you want to do is pass an array of strings to an MVC Action, perhaps something like this:

public class MyController
{
    [HttpPost]
    public ActionResult DoSomething(string[] strings)
    {
       return Json(new {success = true});
    }
}

You can use a JsonResult in an ActionResult to return JSON encoded values, in this case an anonymous type.

To do this in jQuery, the code would look something like this:

function doSomething() {
     var items = ['item1','item2','item3'];
     $.ajax({
         type: 'POST',
         url: 'http://mysite/MyController/DoSomething',
         data: items,
         dataType: 'application/json',
         success: function() {/*handle success here */}
     });
}

Here, all you have to do is populate the items array with the values you want, perhaps y asking the DOM.


you can use something like this:

[in your View]

<script>
var actionUrlHere='@Url.Action("ActionName", "ControllerName")';
$.post(actionUrlHere,
    {
        fieldname_1: fieldValue_1,
        fieldname_2: fieldValue_2,
        fieldname_3: fieldValue_3,
    });
</script>

[In controller]

[HttpPost]
public void AjaxInputSave(string fieldname_1, string fieldname_2, fieldname_3)
    {
...your logic here...
}

or if you want to send array: [in your View]

<script>
var actionUrlHere='@Url.Action("ActionName", "ControllerName")';
var fieldArrayValue = [111,222,333,444];
$.post(actionUrlHere,
    {
        fieldArrayName: fieldArrayValue
    });
</script>

[In controller]

[HttpPost]
public void AjaxInputSave(int [] fieldArrayName)
    {
...your logic here...
}


Here's my $0.02 worth. You might wanna check out @ScottGu's article on the subject. It might be helpfull.This is with respect to MVC3. Here's the link http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx

Hope this sheds some light

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜