简体   繁体   English

如何在不刷新页面的情况下发送和接收数据

[英]How to send and receive data without refreshing the page

I have data in form.我有表格数据。 and I have with click to input (textbox), Send data to mvc controler and Doing the operation in this data and get new data to another textbox.我有点击输入(文本框),将数据发送到 mvc 控制器并在此数据中执行操作并将新数据获取到另一个文本框。

but not refresh page.但不是刷新页面。 How can I use JSON?如何使用 JSON?

If you want to send and get data from the server with form and without refreshing page then you have to use MVC Ajax .如果您想使用表单从服务器发送和获取数据而不刷新页面,那么您必须使用 MVC Ajax BeginForm , In MVC Ajax form provide us ajax option for Before form event, Form success event and form Failed event, I've created a demo for the same you can change event call accordingly your requirement. BeginForm ,在MVC Ajax表单中为我们提供了表单事件之前、表单成功事件和表单失败事件的 ajax 选项,我已经创建了一个演示,您可以根据您的要求更改事件调用。

1. cshtml code as below: 1.cshtml代码如下:

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

    <div class="">
        @using (Ajax.BeginForm("SendOrGetData", "Home", new AjaxOptions { OnSuccess = "OnSucessForm1" }, new { @id = "Form1" }))
        {
            <input type="text" id="textbox1" name="textbox1" />

            <input type="text" id="textbox2" />

            <input type="submit" id="btnSubmit" value="Submit" />
        }
    </div>

    <script>
        function OnSucessForm1(res) {
            $("#textbox2").val(res);
        }
    </script>

2. Controller code as below: 2.控制器代码如下:

        public JsonResult SendOrGetData(string textbox1)
        {
            string res = textbox1;
            return Json(res, JsonRequestBehavior.AllowGet);
        }

Note: I've submitted the form using the button click you can use form trigger event when clicking on the textbox.注意:我已经使用按钮单击提交了表单,您可以在单击文本框时使用表单触发事件。

Ajax call is used for this.为此使用了 Ajax 调用。 For step wise guide follow below link:有关分步指南,请遵循以下链接:

https://www.c-sharpcorner.com/blogs/using-ajax-in-asp-net-mvc https://www.c-sharpcorner.com/blogs/using-ajax-in-asp-net-mvc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM