You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVC5视图与控制器双向数据绑定及SQL查询优化Web应用开发问询

Alright, let's walk through how to set up two-way data binding between your CodeMirror-powered view and an MVC5 controller. Since MVC5 doesn't have built-in two-way binding like newer ASP.NET versions, we'll use a mix of view models, form syncing, and AJAX to make this work seamlessly.

1. First, Create a View Model

We need a model to hold the SQL content from both editors—this will act as the bridge between your view and controller.

public class SqlOptimizerViewModel
{
    public string OriginalSql { get; set; }
    public string OptimizedSql { get; set; }
}
2. Update Your View to Sync CodeMirror with the Model

CodeMirror editors aren't standard form inputs, so we'll use hidden fields to sync their content with the view model. Here's how to adjust your existing code:

@model YourProjectNamespace.SqlOptimizerViewModel

<div id="codeeditor" style="margin-right:20px; float:left">
    <!-- Hidden field tied to the OriginalSql property -->
    @Html.HiddenFor(m => m.OriginalSql, new { id = "originalSqlHidden" })
    
    <script>
        var editor = CodeMirror(document.getElementById("codeeditor"), {
            mode: "sql",
            theme: "dracula",
            tabSize: 5,
            lineNumbers: true,
            value: "@Model.OriginalSql" // Initialize with model data
        });
        editor.setSize(500, 500);
        
        // Sync editor content to hidden field whenever it changes
        editor.on("change", function() {
            document.getElementById("originalSqlHidden").value = editor.getValue();
        });
    </script>
</div>

<div id="codeeditor1">
    <!-- Hidden field tied to the OptimizedSql property -->
    @Html.HiddenFor(m => m.OptimizedSql, new { id = "optimizedSqlHidden" })
    
    <script>
        var editor1 = CodeMirror(document.getElementById("codeeditor1"), {
            mode: "sql",
            theme: "dracula",
            tabSize: 5,
            lineNumbers: true,
            value: "@Model.OptimizedSql" // Initialize with model data
        });
        editor1.setSize(500, 500);
        
        // Optional: Sync back if users modify the optimized SQL
        editor1.on("change", function() {
            document.getElementById("optimizedSqlHidden").value = editor1.getValue();
        });
    </script>
</div>

<input type="submit" value="start" id="btnClick" />
3. Set Up Controller Actions

Create actions to serve the initial view and handle the SQL optimization request:

public class SqlOptimizerController : Controller
{
    // Serve the initial empty view
    public ActionResult Index()
    {
        var model = new SqlOptimizerViewModel();
        return View(model);
    }

    // Handle the optimization request and return updated data
    [HttpPost]
    public JsonResult OptimizeSql(SqlOptimizerViewModel model)
    {
        // Your SQL optimization logic goes here
        // Example: model.OptimizedSql = YourOptimizationService.Optimize(model.OriginalSql);
        
        // Return the updated model as JSON for AJAX
        return Json(model);
    }
}
4. Add AJAX for Smooth Two-Way Interaction

To avoid full page refreshes and enable real-time updates, use AJAX to send data to the controller and update the second editor:

<script src="~/Scripts/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $("#btnClick").click(function(e) {
            e.preventDefault(); // Stop default form submission
            
            // Collect data from the synced hidden fields
            var requestData = {
                OriginalSql: $("#originalSqlHidden").val(),
                OptimizedSql: $("#optimizedSqlHidden").val()
            };
            
            // Send request to controller
            $.ajax({
                url: "@Url.Action("OptimizeSql", "SqlOptimizer")",
                type: "POST",
                data: requestData,
                success: function(updatedModel) {
                    // Update the second editor with the optimized SQL
                    editor1.setValue(updatedModel.OptimizedSql);
                    // Sync back to the hidden field
                    $("#optimizedSqlHidden").val(updatedModel.OptimizedSql);
                },
                error: function(xhr) {
                    console.error("Error optimizing SQL: " + xhr.responseText);
                }
            });
        });
    });
</script>
Key Things to Remember
  • Sync CodeMirror to Hidden Fields: This is critical because MVC can't directly read values from CodeMirror editors—hidden fields act as intermediaries for model binding.
  • AJAX for Real-Time Updates: Using AJAX makes the interaction feel like true two-way binding, with no page reloads.
  • Validation: If you need to validate user input, add data annotations to your view model and handle validation errors in the controller/AJAX response.

内容的提问来源于stack exchange,提问作者Rostyslav Fedyk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:28:36