Send to and get value from a MVC3 controller by AJAX - asp.net-mvc-3

I have a html input text field and a button.
I want to take user input value from that html text field by clicking that button and want to send that value (by AJAX) into a MVC3 Controller ( as like as a parameter of an ActionResult setValue() ) ?
An other thing i want to know that, how i can get a return value (that return by a ActionResult getValue() ) from a MVC3 Controller and set it in a html text field (by AJAX) ?
please help me with a good example, please. and sorry for my bad English. :)

Button click event
$(document).ready(function ()
{
$('#ButtonName').click(function ()
{
if ($('#YourHtmlTextBox').val() != '')
{
sendValueToController();
}
return false;
});
});
You call your ajax function like so:
function sendValueToController()
{
var yourValue = $('#YourHtmlTextBox').val();
$.ajax({
url: "/ControllerName/ActionName/",
data: { YourValue: yourValue },
cache: false,
type: "GET",
timeout: 10000,
dataType: "json",
success: function (result)
{
if (result.Success)
{ // this sets the value from the response
$('#SomeOtherHtmlTextBox').val(result.Result);
} else
{
$('#SomeOtherHtmlTextBox').val("Failed");
}
}
});
}
This is the action that is being called
public JsonResult ActionName(string YourValue)
{
...
return Json(new { Success = true, Result = "Some Value" }, JsonRequestBehavior.AllowGet);
}

Related

Ajax post method returns undefined in .net mvc

I have this ajax post method in my code that returns undefined. I think its because I have not passed in any data, any help will be appreciated.
I have tried passing the url string using the #Url.Action Helper and passing data in as a parameter in the success parameter in the ajax method.
//jquery ajax post method
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action("Bookings/SaveBooking")',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
//controller action
[HttpPost]
public JsonResult SaveBooking(Booking b)
{
var status = false;
using (ApplicationDbContext db = new ApplicationDbContext())
{
if (b.ID > 0)
{
//update the event
var v = db.Bookings.Where(a => a.ID == a.ID);
if (v != null)
{
v.SingleOrDefault().Subject = b.Subject;
v.SingleOrDefault().StartDate = b.StartDate;
v.SingleOrDefault().EndDate = b.EndDate;
v.SingleOrDefault().Description = b.Description;
v.SingleOrDefault().IsFullDay = b.IsFullDay;
v.SingleOrDefault().ThemeColor = b.ThemeColor;
}
else
{
db.Bookings.Add(b);
}
db.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status } };
}
Before the ajax call, you should collect the data in object like,
var requestData= {
ModelField1: 'pass the value here',
ModelField2: 'pass the value here')
};
Please note, I have only added two fields but as per your class declaration, you can include all your fields.
it should be like :
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action(Bookings,SaveBooking)',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
Try adding contentType:'Application/json', to your ajax and simply have:
return Json(status);
In your controller instead of JsonResult. As well as this, You will need to pass the data in the ajax code as a stringified Json such as:
data:JSON.stringify(data),
Also, is there nay reason in particular why it's a JsonResult method?

Pass ViewModel + Parameter to action using ajax call

How do I pass a view model and another parameter to my action method using jquery ajax?
with what I'm doing now, the action method is not being called. I think the cause is probably because the parameters are not being passed correctly in the data object of the jquery ajax call:
jQuery ajax:
$('#form-login').submit(function (event) {
event.preventDefault();
$.ajax({
url: "/Account/LogOn/",
data: $('#form-login').serialize(),
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.userAuthenticated) {
window.location.href = data.url;
} else {
formBlock.clearMessages();
displayError($('#errorcred').val());
}
},
error: function () {
formBlock.clearMessages();
displayError($('#errorserver').val());
}
});
});
Action method (which accepts the view model and another parameter):
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
// Validate the email and password
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
if (Request.IsAjaxRequest())
{
return Json(new { userAuthenticated = true, url = returnUrl, isRedirect = true });
}
else
{
return Redirect(returnUrl);
}
}
else
{
if (Request.IsAjaxRequest())
{
return Json(new { userAuthenticated = true, url = Url.Action("Index", "Home"), isRedirect = true });
}
else
{
return RedirectToAction("Index", "Home");
}
}
}
}
else
{
if (Request.IsAjaxRequest())
{
return Json(new { userAuthenticated = false, url = Url.Action("LogOn", "Account") });
}
else
{
ModelState.AddModelError("", adm.ErrorUserNamePassword);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Remove the following from the $.ajax call:
contentType: 'application/json; charset=utf-8',
You have specified application/json encoding but the $('#form-login').serialize() function is sending application/x-www-form-urlencoded content.
As far as sending the returnUrl parameter is concerned, you could simply read it from the form action where it should be present (if you used the Html.BeginForm() helper):
$.ajax({
url: this.action,
...
});
Also you probably want to rename the event variable with something else as this is a reserved word in javascript:
$('#form-login').submit(function (e) {
e.preventDefault();
...
});
The only way I have found to do this is to just include the second parameter in your viewmodel and continue to serialize your form the way you are doing now.

how to pass parameters to actionreuslt using jquery mvc 3 razor?

i am new in mvc3 razor my prob is :
i have this actionResult method that can receive variables from jquery method
why my variables comes NULL
csharp :
public ActionResult GetOrdersSP(int? StoreId, int? SupplierId)
{
bool count = false;
var model = _storeOrderService.GetStoreSuppOrders(StoreId, SupplierId);
if (model.Count() > 0)
{
count = true;
return Json(count, JsonRequestBehavior.AllowGet);
}
else
{
return Json(count, JsonRequestBehavior.AllowGet);
}
}
and this is my jquery
$.fn.GetCount = function (data) {
var storeid = $('#StoreId').val();
var Supplierid = $('#Supplierid').val();
if (ValidateCreateOrder('#StoreId', '#Supplierid')) {
alert(storeid);
alert(Supplierid);
$.ajax(
{
url: '<%: Url.Action("GetOrdersSP", "StoreOrder")%>',
type: 'json',
data: { StoreId: $('#StoreId').val(),
SupplierId: $('#SupplierId').val()
},
success: function (json) {
//should popup the modal
alert(true);
}
});
}
}
please note that the storeid and supplierid are displayed correctly in the alert
thanks
I think you need to convert your data to json and parse it on actionResult.
See this post Pass a parameter to a controller using jquery ajax

Invalid Json data return page content

I call a controller action using jquery ajax (see the below code), After the action has been executed, An Invalid Json error was raised. And I've notice that, it returns the page content. Why did it happen. can Anyone help me to solve this problem?
Controller
[HttpGet]
public ActionResult ViewDetails(int id)
{
var eventsdetails = _service.GeteventByID(id);
return View("EventDetails",eventsdetails);
}
[HttpPost]
public ActionResult UpdateAnswers(string answers, string question, string controlid, int eventid)
{
var replacetext=string.Empty;
if (answers.Length>0)
replacetext = answers.Replace("\n", ",");
_service.UpdateAnswers(eventid, replacetext, controlid);
return RedirectToAction("ViewDetails", new { id = eventid });
}
Javascript
function dropdownlist(controlid, title, answers, eventid) {
var $answersreplaced = answers.replace( /\,/g , " \r");
var $deleteDialog = $('<div><textarea id="answerlist" rows="10" cols="50">' + $answersreplaced + '</textarea><div><div style="font-size:9px">(To change back to an open answer field, delete all choices above and save)</div>');
$deleteDialog.dialog({
resizable: false,
height: 280,
width: 350,
title: title + " - Edit Choices",
modal: true,
buttons: {
"Save": function () {
$.ajax({
type: 'POST',
url: '#Url.Action("UpdateAnswers")',
dataType: 'json',
data: { answers: $('#answerlist').val(),
question: title,
controlid: controlid,
eventid: eventid
},
success: function (result) {
$(this).dialog("close");
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
// alert('there was a problem saving the new answers, please try again');
}
});
},
Cancel: function () {
$(this).dialog("close");
}
}
});
};
It's because you're not returning a JsonResult from the action, you're redirecting to another action, which in turn returns a ViewResult.
Try something like this:
[HttpPost]
public ActionResult UpdateAnswers(string answers, string question, string controlid, int eventid)
{
var replacetext=string.Empty;
if (answers.Length>0)
replacetext = answers.Replace("\n", ",");
_service.UpdateAnswers(eventid, replacetext, controlid);
var eventsdetails = _service.GeteventByID(eventid);
return Json(eventdetails);
}
You specify dataType: 'json' in your AJAX request and inside your UpdateAnswers controller action you return RedirectToAction which obviously redirects to the ViewDetails action which in turn returns a view which in turn is HTML. So this doesn't make sense.
You have to return Json from the UpdateAnswers controller action instead of redirecting.

Removing a Partial View in MVC

I have a View with Name, CreatedDate, Address, etc. In the Address section I have State, City etc. I made this section a Partial View.
By default there will be one address section in mainView. I have a button "AddAddress". I want to add another address section if user clicks the button (add a partial view). After getting this partial view there should be a remove button to remove this partial view. I am not using Razor.
the following code is my Javascript to delete my address.
function deleteAddress(addressId, clientId) {
var url1 = "/Client/DeleteAddress";
if (confirm("Are you sure you want to delete this address?")) {
var result = false;
$.ajax({
url: url1,
type: 'POST',
async: false,
data: { AddressId: addressId, ClientId: clientId },
dataType: 'json',
success: function (data) {
result = data;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
}
});
if (result) {
}
}
}
the following code is in my controller.
[HttpPost]
public JsonResult DeleteAddress(int AddressId, int ClientId)
{
if (AddressId != 0)
{
if (ClientId != 0)
{
ClientService.Client clientVuTemp = new ClientService.Client();
clientVuTemp = (ClientService.ClientView)TempData["EditClientData"];
clientVuTemp.Address.RemoveAt(AddressId);
//soft delete
clientVuTemp.Address[AddressId].IsActive = false;
_clientSvc.InserOrUpdateClientAddresses(clientVuTemp.Address);
}
else
{
}
return Json(true);
}
else
return Json(false);
}
In the Model we can have a property like IsAddAddressEnabled, Onclick on AddAddress you can set this as true and onclick on cancel you can set as false.
In View you can put an condition,
#if(Model.IsAddAddressEnabled)
{
Html.Partail(....)
}

Resources