ASP.NET MVC模型与serialize绑定

时间:2015-05-07 03:31:15

标签: jquery json asp.net-mvc model-binding

我正在使用class CalculatorViewController: MQLoadableViewController { let calculationQueue: NSOperationQueue // Initialized in init() var calculation: Calculation? var countdownTimer: NSTimer? func recalculate() { if let profile = AppState.sharedState.currentProfile { // Cancel all calculation operations. self.calculationQueue.cancelAllOperations() let calculateOperation = self.createCalculateOperation(profile) self.calculationQueue.addOperation(calculateOperation) } } func decayCalculation() { if let calculation = self.calculation { // tick() subtracts 1 second from the timer and adjusts the // hours and minutes accordingly. Returns true when the timer // goes down to 00:00:00. let timerFinished = calculation.timer.tick() // Pass the calculation object to update the timer label // and other things. if let mainView = self.primaryView as? CalculatorView { mainView.calculation = calculation } // Invalidate the timer when it hits 00:00:00. if timerFinished == true { if let countdownTimer = self.countdownTimer { countdownTimer.invalidate() } } } } func createCalculateOperation(profile: Profile) -> CalculateOperation { let calculateOperation = CalculateOperation(profile: profile) calculateOperation.successBlock = {[unowned self] result in if let calculation = result as? Calculation { self.calculation = calculation /* Hide the loading screen, show the calculation results, etc. */ // Create the NSTimer. if self.countdownTimer == nil { self.countdownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("decayCalculation"), userInfo: nil, repeats: true) } } } return calculateOperation } } serialize方法对我的ASP.NET MVC应用程序进行Ajax调用。 MVC无法绑定模型。

这是我的JS代码和强类型视图:

JSON.stringify

请求的有效负载如下所示:

<script>
    function saveDetails() {
        jsonObj = $('#rdform').serialize();
        $.ajax({
            method: "POST",
            url: "R/SaveDetail",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            data: JSON.stringify(jsonObj)
        });
    }
</script>

<form id="rdform">
    <div>
        <div>
            @Html.LabelFor(m => m.LiIdH)
            @Html.TextBoxFor(m => m.LiIdH)
        </div>
        <div>
            @Html.LabelFor(m => m.LiIdR)
            @Html.TextBoxFor(m => m.LiIdR)
        </div>
    </div>
    <input type="button" onclick="saveDetails()" />
</form>

这是我的行动方法:

"LiIdH=1&LiIdD=&LiIdR=2"

我错过了什么吗?

1 个答案:

答案 0 :(得分:4)

您遇到麻烦的原因是您使用了serialize和JSON.stringify。 form.serialize返回一个字符串值,当传递给JSON.serialize时,它会被一对额外的引号括起来。您调用操作方法的最简单方法是删除对 JSON.stringify 的调用,并删除ajax调用的 contentType 选项并使用默认值,如下图所示:

<script>
    function saveDetails() {
        $.ajax({
            method: "POST",
            url: "R/SaveDetail",
            dataType: "json",
            data: $('#rdform').serialize()
        });
    }
</script>