开发者

How to Update TextBox in MVC Ajax

How do i update textbox using MVC Ajax UpdateTargetId option.?

I am new to MVC Ajax applications. Please a开发者_运维知识库ny one help me out.

Thanks, Pon Kumar Pandian .T


you can achieve that simple concept using

1- Post\Get

2- Ajax

Note: just replace the $("#myform").html() with $("#mytext").text = "data"

1- Using Get\Post

/////// Controller post and get simple text value 
[HttpPost]
    public string Contact(string message)
    { 
        return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
    }

//// in the view add reference to the Javascript (jQuery) files

@section Scripts{

<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>  
}

/// then add the Post method as following:

<script type="text/javascript"> 

/// post and get text value

$("#send").on("click", function () {    
$.post('', { message: $('#msg').val() })  

//// empty post('') means post to the default controller, 
///we are not pacifying different action or controller
/// however we can define a url as following:
/// var url = "@(Url.Action("GetDataAction", "GetDataController"))"

         .done(function (response) {
             $("#myform").html(response);
        })
        .error(function () { alert('Error') })
        .success(function () { alert('OK') })
        return false;
    }); 

   </script>

2-Also you can use Get only as following:

   /////Controller = Home
   //// Action = FullName
   ///// get only simple text message
    [HttpGet]
    public string FullName()
    { 
        return "full Name: Mahmoud Sayed";
    }

/// in the view:

 $("#getfullname").on("click", function () {
        var url = "@(Url.Action("FullName", "Home"))"
            $.get(url, {   })
            .done(function (response) {
                $("#myform").html(response)
            })
            .error(function () { alert('Error') })
            .success(function () { alert('OK') })
            return false;
        });
   </script>

3- Now let's say you want to do it using $.Ajax and JSON:

// Post JSON data  add using System.Net;
    [HttpPost]
    public JsonResult JsonFullName(string fname, string lastname)
    {
        var data = "{ \"fname\" : \"" + fname  + " \" , \"lastname\" : \"" + lastname + "\" }";
//// you have to add the JsonRequestBehavior.AllowGet 
 //// otherwise it will throw an exception on run-time.
        return Json(data, JsonRequestBehavior.AllowGet);  
    }

Then, inside your view: add the event click on a an input of type button, or even a from submit: Just make sure your JSON data is well formatted.

  $("#jsonGetfullname").on("click", function () { 
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "@(Url.Action("JsonFullName", "Home"))",
            data: "{ \"fname\" : \"Mahmoud\" , \"lastname\" : \"Sayed\" }",
            dataType: "json",
            success: function (data) {
                var res = $.parseJSON(data);
                $("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
            }, 
            error: function (xhr, err) {
                alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
                alert("responseText: " + xhr.responseText);
            } 
        })
    });

   </script>

cheers,

Mahmoud Sayed


You can simply wrap all you want to update in some div with id same that you're putting in UpdateTargetId property, and return new content(new textbox with new value). And also don't forget to set Ajax updating type to replace(not append).


We can't give the textbox control id directly in UpdateTargetId property. Bur we can do work around to achieve this. Please fine the blow mention code for the same.

//This the call back method once the ajax request has been successes.

function fnOnSuccess(context) {

        alert(context); //this context having all the current ajax req & res information.

        var response = context.get_data(); //Using this get_data() method we can get the response from server.

        $('#txtajaxResponse')[0].value = response;    
    }


<!-- Code in .aspx page -->
<%=Ajax.ActionLink("TextBox in UpdateTargetId","GetInfo","Ajax",new AjaxOptions{OnSuccess = "fnOnSuccess"}) %>

<%=Html.TextBox("txtajaxResponse")%>

Thanks, Pon Kumar Pandian .T

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜