使用jQuery数据发布到MVC操作方法 [英] Use Jquery to post data to MVC action method

查看:181
本文介绍了使用jQuery数据发布到MVC操作方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想张贴使用下面的方法使用jQuery AJAX MVC的操作数据。但里面的控制器上的所有模特属性始终是空。不知道我在这里缺少

.CSHTML

 <形式ID =MyForm的>
<输入名称=PersonName的类型=文本/>
<输入名称=地址类型=文本/>
<选择名称=美国多个=多​​>
    <期权价值=TX>德州< /选项>
    <期权价值=OK>俄克拉何马< /选项>
    <期权价值=OH>俄亥俄州< /选项>
< /选择>
<选择名称=状态>
    <期权价值=1>的Active< /选项>
    <期权价值=2>删除< /选项>
    <期权价值=3>挂起< /选项>
< /选择>
<输入类型=按钮值=保存ID =保存/>
 

的JavaScript

  $(函数(){
$(#保存)。点击(函数(五){
    VAR dataToPost = $(#MyForm的)。序列化()
    $阿贾克斯(
    {
        键入:POST,
        数据:JSON.stringify(dataToPost)
        网址:工作/保存,
        的contentType:应用/ JSON的;字符集= UTF-8
    })
  })
})
 

控制器

 公共类WorkingController:控制器
{
    // GET:工作
    公众的ActionResult指数()
    {
        返回查看();
    }

    公众的ActionResult保存(WorkingModel模型)
    {
        //所有模特属性为null这里????

        返回JSON(成功);
    }
 }
 

型号

 公共类WorkingModel
{
    公共字符串PersonName的{获得;组; }
    公共字符串的地址{获得;组; }
    公共字符串[]国家{获得;组; }
    公共字符串状态{获得;组; }
}
 

EDIT1
我已经加入上述模型。在这里,序列化的数据和JSON字符串化数据时,我点击保存。

序列化数据
PersonName的=美孚和放大器;地址= 123 +测试+驱动器和放大器;美国= TX与放大器;状态= 1

在JSON.Stringify
\PersonName的=美孚和放大器;地址= 123 +测试+驱动器和放大器;美国= TX与放大器;状态= 1 \

我已经尝试添加HttpPost属性和[FromBody]没有运气属性。
我不认为我必须从的ActionResult到JsonResult更改返回类型
另外URL正确beacuase调试器击中操作方法,我可以快速监视的模特属性里面。

请注意,它的作品,如果我创建JSON对象,并张贴像下面

  VAR dataToPost = {
    PersonName的:'富',
    地址:'123试驾,
    状态:TX,
    状态:1
 }
 

解决方案

您的JavaScript / jQuery的code可以显著简化,这可能是最好的路线走:

  $(函数(){
    $(#MyForm的)。在('提交',函数(E){

        即preventDefault()// prevent表单的正常提交

        VAR dataToPost = $(本).serialize()

        $。员额(工作/保存,dataToPost)
            .done(函数(响应状态,jqxhr){
                //这是成功的回调
            })
            .fail(功能(jqxhr,状态,错误){
                //这是错误回调
            })
    })
})
 

您应该处理表单的的onsubmit 事件,而不是的onclick 按钮的事件 - 这是可能的的东西比其他按钮以使表单提交。在这种情况下,我们要prevent形式的默认提交的行为,因为我们正在使用AJAX提交表单。

.serialize()已正确处理编码的形式,所以你不需要JSON-CN code中的表单值。否则,很有可能是在处理请求时ModelBinder的不重建模式的原因。

$交是一个辅助功能,它包装你需要的 $ AJAX 共同设置工作 - 在这里显示的版本要张贴到的URL,这些数据POST。如果你的jQuery的code是在一个视图脚本元素,那么你可能想使用 Url.Action()帮手 - 这将构建基于正确的URL在你的路由规则。如果您选择走这条路,你会使用类似的东西:

  $。员额(@ Url.Action(保存,工作),dataToPost)
 

然后,我们用相关助手处理(用HTTP-200状态code任何东西)成功的响应和故障响应(别的,基本上)。你的做什么的那些助手是由你。

I'm trying to post data using jquery ajax to mvc action using the approach below. But inside controller all model properties are always null. Not sure what im missing here

.CSHTML

<form id="MyForm">
<input name="PersonName" type="text" />
<input name="Address" type="text" />
<select name="States" multiple="multiple">
    <option value="TX">Texas</option>
    <option value="OK">Oklahoma</option>
    <option value="OH">Ohio</option>
</select>
<select name="Status">
    <option value="1">Active</option>
    <option value="2">Deleted</option>
    <option value="3">Pending</option>
</select>
<input type="button" value="Save" id="Save" />

JavaScript

$(function () {
$("#Save").click(function (e) {
    var dataToPost = $("#MyForm").serialize()
    $.ajax(
    {
        type: "POST",
        data: JSON.stringify(dataToPost),
        url: "Working/Save",
        contentType: 'application/json; charset=utf-8'
    })
  })
})

Controller

public class WorkingController : Controller
{
    // GET: Working
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Save(WorkingModel model)
    {
        // All model properties are null here????

        return Json("Success");
    }
 }

Model

public class WorkingModel
{
    public string PersonName { get; set; }
    public string Address { get; set; }
    public string[] States { get; set; }
    public string Status { get; set; }
}

EDIT1
I have added the model above. Here the serialized data and JSON stringify data when i click on save.

Serialized data
"PersonName=Foo&Address=123+Test+Drive&States=TX&Status=1"

After JSON.Stringify
"\"PersonName=Foo&Address=123+Test+Drive&States=TX&Status=1\""

I have tried adding HttpPost attribute and [FromBody] attribute with no luck.
I don't think i have to change return type from "ActionResult" to "JsonResult".
Also Url is correct beacuase debugger is hitting inside the action method where i can QuickWatch the model properties.

Note that It works if i create json object and post it like below

var dataToPost = {
    PersonName:'Foo',
    Address: '123 Test Drive',
    State: 'TX',
    Status: 1
 }

解决方案

Your JavaScript/jQuery code can be significantly simplified, which might be the best route to go:

$(function () {
    $("#MyForm").on('submit', function (e) {

        e.preventDefault() // prevent the form's normal submission

        var dataToPost = $(this).serialize()

        $.post("Working/Save", dataToPost)
            .done(function(response, status, jqxhr){ 
                // this is the "success" callback
            })
            .fail(function(jqxhr, status, error){ 
                // this is the ""error"" callback
            })
    })
})

You should handle the onsubmit event of the form, rather than the onclick event of the button - it's possible for something other than the button to cause the form to be submitted. In this case, we want to prevent the form's default submit behavior, since we're submitting the form with AJAX.

.serialize() already handles encoding the form correctly, so you don't need to JSON-encode the form values. Doing so is most likely the reason that the modelbinder isn't rebuilding the model when processing the request.

$.post is a helper function that wraps the common setup work you need for $.ajax - the version shown here wants the URL to POST to, and the data to POST. If your jQuery code is in a script element within a View, then you probably want to use the Url.Action() helper - it will build the correct URL based on your routing rules. If you elect to go that route, you would use something similar to:

$.post('@Url.Action("Save", "Working")', dataToPost)

Then, we handle the successful response (anything with a HTTP-200 status code) and the failed response (anything else, basically) using the relevant helpers. What you do in those helpers is up to you.

这篇关于使用jQuery数据发布到MVC操作方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆