Skip to main content
 首页 » 编程设计

javascript之使用ajax将数据从文本框提交到asp net mvc Controller

2024年01月26日35kerrycode

我有这个

查看

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @class = "form-inline", role = "form" })) 
    { 
        @Html.TextBox("SearchString", ViewBag.SearchFilter as string, new { @class = "form-control", onclick="keystroke()", id = "search" }) 
    } 

Controller

//GET: Home 
public async Task<ActionResult> Index(MyViewModel model) 
            { 
                //... 
                if (model.SearchString != null) 
                { 
                    //... 
                    var myString = model.SearchString; 
                    var b = model.FirstInt 
                } 
                //... 
                return View(model); 
            } 

View 模型

public class MyViewModel 
{ 
//... 
    public string SearchString { get; set; } 
    public int? FirstInt { get; set; } 
} 

Javascript

function keystroke() { 
        var firstint = 1; 
        $("#search").keypress(function(event) { 
            if (event.which === 13) { 
                event.preventDefault(); 
                $("form").submit(function() { 
                    var text = $('#SearchString').val(); 
                    sendForm(firstint, text); 
                }); 
            } 
        }); 
    } 
function sendForm(firstint, text) { 
            var data = {FirstInt: firstint, SearchString: text} 
            $.ajax({ 
                url: "Home/Index", 
                type: 'POST', 
                data: data, 
                success: function () { 
                    alert('success'); 
                } 
            }); 
        }; 

它不起作用。

我想当用户在搜索输入中按下 Enter 键时,我将他输入的文本和 firstint 的值发送到 Controller 。如果我删除所有 javasript,然后按 Enter 全部通常发送到 Controller ,但我也需要 firstint 值。

请您参考如下方法:

使用Ajax.BeginForm的例子,需要引用

jquery.unobtrusive-ajax.js

否则它会像普通的 Html.BeginForm。

查看:

@using (Ajax.BeginForm("Index", "Home",  
    new AjaxOptions { HttpMethod = "Post", OnFailure = "OnFailure", OnSuccess = "OnSuccess" })) 
{ 
    <input type="text" name="Id" /> 
    // Your HTML inside  your form... 
    <button type="submit">Submit Form</button> 
} 

Controller :

[HttpPost] 
public ActionResult Index(FormCollection collection) 
{ 
    var Id = collection["Id"]; 
    return View(); 
} 

Javascript:

<script> 
    function OnFailure(x, s, e) { 
        alert(e); 
        // More code here... 
    } 
    function OnSuccess(d) { 
        alert(d); 
        // More code here... 
    } 
</script> 

希望这对您有所帮助。