How to Update TextBox in MVC Ajax - ajax

How do i update textbox using MVC Ajax UpdateTargetId option.?
I am new to MVC Ajax applications. Please any 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

Related

MVC Controller getting 404 error

I have an MVC controller that has several Methods on it. One to show the View, 6 that are for jquery ajax methods. The View shows up correctly and here is the simple code
public ActionResult Queues()
{
return View();
}
On that view there are 2 datatable.net grids. That grid gets populated with a ajax call to this
[HttpGet]
public async Task<JsonResult> QueueOne()
{
try
{
....
var results = await GetData(queryString, authUser.AccessToken).ConfigureAwait(false);
var jsonObj = JsonConvert.DeserializeObject<DataTableWrapper<QueueItemForRead>>(results);
return Json(jsonObj, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Logger.Error(ex.Message, ex);
}
return Json("Error occured please try again");
}
which populates the grid correctly.
I have other functions on the page that call another endpoint on the page
public async Task<JsonResult> ItemComplete(Guid QueueId, long version)
{
try
{
...
var results =
await
PutData(queryString, JsonConvert.SerializeObject(itemCompleted), authUser.AccessToken)
.ConfigureAwait(false);
var jsonObj = JsonConvert.DeserializeObject<NewItemCommandResult>(results);
return Json(jsonObj, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Logger.Error(ex.Message, ex);
}
return Json("Error occured please try again");
}
and here is the JS that calls the above endpoint
$.ajax({
url: 'http://localhost:18171/Clients/CurrentActivity/ItemComplete' + "?QueueId=" + data + "&version=" + version,
type: 'PUT',
//contentType: 'application/json',
//dataType: 'json',
success: function (result) {
if (result.Result === 2) {
showSuccessNotification(name +
" has been Delivered to table.",
"Food Delivered");
}
//else {
//}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//Process error actions
console.log(XMLHttpRequest.status + ' ' +
XMLHttpRequest.statusText);
$(buttonName).hide();
},
beforeSend: function () {
// Code to display spinner
$(buttonName).hide();
$(completedAjax).show();
},
complete: function () {
// Code to hide spinner.
$(completedAjax).hide();
}
});
but everytime this function is run all I get a 404 error.
Sorry it was bad cut and paste job, the URL actually has signle quotes around it. and i get the base Url this way
var QueueUrl = '#Url.Action("QueueOne","CurrentActivity")';
so when it renders the actual url is '/Clients/CurrentActivity/QueueOne'
your url doesn't contain " " Or ' ' so it isn't considered as string it should be like
url: "/Clients/CurrentActivity/ItemComplete?QueueId=" + data + "&version=" + version,
Don't Use Your Local Domain IN the Url This Will Cause Problem In production Version if you forget to change it
you can also use Url Helper To Make valid Url Like
url: "#Url.Action("ItemComplete","CurrentActivity",new{area='Clients'})"+"'QueueId=' + data + "&version=" + version,

ajax calls the mvc controller

why this code does not work?.I receive "ok" but i can not see the view1 (view1 not loaded).I want to manage the views by prop1 .If the value of prop1="1" load view1
Hier is my controller
[System.Web.Mvc.Route("Home/SubmitMyData/")]
[System.Web.Http.HttpPost]
public ActionResult SubmitMyData([FromBody]MyParamModel mydata)
{
if (mydata.Prop1.Equals("1"))
return View("veiw1");
else
return View("view2");
}
public class MyParamModel // #4
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
and it is my ajax call
$('#Buttonv').click(function () {
var myData = {Prop1: "1", Prop2: ""}; // #1
$.ajax({
type: 'POST',
data: myData, // #2
url: '/Home/SubmitMyData',
})
.success(function (data) {
var output = "ok";
$('#lblmessage').html(output);
})
.error(function (xhr, ajaxoption, thrownError) {
$('#lblmessage').html("moshkelo" + xhr + "ajaxoption= " + ajaxoption + " throwerror=" + thrownError);
});
//return false;
});
If you are returning a View from your Controller, you'll need to ensure that you are actually using the HTML content within the success callback of your POST :
.success(function (data) {
// data will contain your content
$('#lblmessage').html(data);
})
You were previous using output, which didn't seem to be defined anywhere within your script.
Additionally, you may want to check the name of the view that you are returning as return View("veiw1"); seems like a typo that should be return View("View1");.
In your javascript, you are ignoring the HTML returned by the server. Try changing it to...
.success(function (data) {
$('#lblmessage').html(data);
})
Per the documentation, the first parameter to the success method is the data returned by the server.

Random HTTP error 405 while using ajax request

I am getting HTTP error 405 verb not allowed. As sometimes code works and sometimes throws http 405 error, I need to understand whether this is programming problem or server configuration problem. I am using ajax with jquery. I have gone through all related posts here and tried all recommended options related with the code. Please help.
my javascript code is as follows
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#name_error").show();
$("input#email").focus();
return false;
}
var textquery = $("textarea#textquery").val();
if (textquery == "") {
$("label#name_error").show();
$("textarea#textquery").focus();
return false;
}
var dataString = name + email + textquery;
// alert (dataString);return false;
$.ajax({
type: "POST",
url: "samplemail.aspx",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form <br> Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
});
runOnLoad(function(){
$("input#name").select().focus();
});
Problem solved
the way Of passing parameter was wrong i.e.data : datastring .
The correct way is data : { name : name, email: email, textquery: textquery}

How to include the #Html.AntiForgeryToken() when deleting an object using a Delete link

i have the following ajax.actionlink which calls a Delete action method for deleting an object:-
#if (!item.IsAlreadyAssigned(item.LabTestID))
{
string i = "Are You sure You want to delete (" + #item.Description.ToString() + ") ?";
#Ajax.ActionLink("Delete",
"Delete", "LabTest",
new { id = item.LabTestID },
new AjaxOptions
{ Confirm = i,
HttpMethod = "Post",
OnSuccess = "deletionconfirmation",
OnFailure = "deletionerror"
})
}
but is there a way to include #Html.AntiForgeryToken() with the Ajax.actionlink deletion call to make sure that no attacker can send a false deletion request?
BR
You need to use the Html.AntiForgeryToken helper which sets a cookie and emits a hidden field with the same value. When sending the AJAX request you need to add this value to the POST data as well.
So I would use a normal link instead of an Ajax link:
#Html.ActionLink(
"Delete",
"Delete",
"LabTest",
new {
id = item.LabTestID
},
new {
#class = "delete",
data_confirm = "Are You sure You want to delete (" + item.Description.ToString() + ") ?"
}
)
and then put the hidden field somewhere in the DOM (for example before the closing body tag):
#Html.AntiForgeryToken()
and finally unobtrusively AJAXify the delete anchor:
$(function () {
$('.delete').click(function () {
if (!confirm($(this).data('confirm'))) {
return false;
}
var token = $(':input:hidden[name*="RequestVerificationToken"]');
var data = { };
data[token.attr('name')] = token.val();
$.ajax({
url: this.href,
type: 'POST',
data: data,
success: function (result) {
},
error: function () {
}
});
return false;
});
});
Now you could decorate your Delete action with the ValidateAntiForgeryToken attribute:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
...
}
Modifying the answer by Bronx:
$.ajaxPrefilter(function (options, localOptions, jqXHR) {
var token, tokenQuery;
if (options.type.toLowerCase() !== 'get') {
token = GetAntiForgeryToken();
if (options.data.indexOf(token.name)===-1) {
tokenQuery = token.name + '=' + token.value;
options.data = options.data ? (options.data + '&' + tokenQuery)
: tokenQuery;
}
}
});
combined with this answer by Jon White
function GetAntiForgeryToken() {
var tokenField = $("input[type='hidden'][name$='RequestVerificationToken']");
if (tokenField.length == 0) { return null;
} else {
return {
name: tokenField[0].name,
value: tokenField[0].value
};
}
Edit
sorry - realised I am re-inventing the wheel here SO asp-net-mvc-antiforgerytoken-over-ajax/16495855#16495855

Converting MVC Ajax to Jquery

I am in the process of learning how to convert MVC Ajax to jquery ajax so I can do more.
This is the old ajax, I took out the loading stuff
#Ajax.ActionLink("Update Tweets", "Index", "Home",
new AjaxOptions
{
UpdateTargetId = "TweetBox",
InsertionMode = InsertionMode.InsertBefore,
HttpMethod = "Get",
})
I need to convert this to jquery ajax. It seems to be working lets see the code
<script>
$(document).ready(function () {
$("#StartLabel").click(function (e) {
$.ajax({
type: "Get",
url: '/Home/Index',
// data: "X-Requested-With=XMLHttpRequest",
// contentType: "application/text; charset=utf-8",
dataType: "text",
async: true,
// cache: false,
success: function (data) {
$('#TweetBox').prepend(data);
alert('Load was performed.');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
});
});
</script>
In the microsoft ajax it sets XML Request in the headers. Do I need to add that too? I am just paging my controller that performs a query to twitter and appends the data to the top.
I am using fiddler to see how the requests are different but the results are the same.
I also noticed if i put the text in the data: object its puts it in the header. i dont think that is right by any means.
You could define a normal anchor:
#Html.ActionLink("Update Tweets", "Index", "Home", null, new { id = "mylink" })
And then unobtrusively AJAXify it:
$(document).ready(function () {
$("#mylink").click(function (e) {
$.ajax({
type: "GET",
url: this.href,
success: function (data) {
$('#TweetBox').prepend(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
return false;
});
});
Notice that I return false from the click handler in order to cancel the default action. Also notice that I am using the anchor's href property instead of hardcoding it.
The 2 AJAX requests should be identical.
Here is simple example using Ajax with Jason data
// Post JSON data
[HttpPost]
public JsonResult JsonFullName(string fname, string lastname)
{
var data = "{ \"fname\" : \"" + fname + " \" , \"lastname\" : \"" + lastname + "\" }";
return Json(data, JsonRequestBehavior.AllowGet);
}
in the view add a reference to the query as following
#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>
}
in the view add the js
note: (jsonGetfullname).on is a button
<script type="text/javascript">
$("#jsonGetfullname").on("click", function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "#(Url.Action("JsonFullName", "Home"))",
data: "{ \"fname\" : \"modey\" , \"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>
you can also use (POST\GET) as following:
[HttpPost]
public string Contact(string message)
{
return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
}
in the view add the js
note: (send).on is a button
$("#send").on("click", function () {
$.post('', { message: $('#msg').val() })
.done(function (response) {
setTimeout(function () { $("#myform").html(response) }, 2000);
})
.error(function () { alert('Error') })
.success(function () { alert('OK') })
return false;
});

Resources