How to handle $.ajax - asp.net

I want to send JSON data to an action that will update some data. I then want to either redirect to another action or send back an error message to $.ajax.
Is possible with $.ajax otherwise how can I?
Becase following code does not redirect.
[code]
[HttpPost]
public ActionResult Save(RecipeViewModel postdata)
{
Recipe recipe = postdata.GetRecipe(_user.UserID);
int recipeid = _service.AddRecipe(recipe, null, true);
foreach (Ingredient ing in recipe.Ingredients)
{
ing.RecipeID = recipeid;
_service.AddIngredient(ing, null, false);
}
if (!postdata.Comment.IsEmpty())
{
Comment comment = new Comment();
comment.fldComment = postdata.Comment;
comment.RecipeID = recipeid;
comment.UserID = _user.UserID;
comment.EnteredByName = _user.Names;
comment.EnteredOn = DateTime.Now.ToString();
_service.AddComment(comment, null, false);
}
_service.SubmitChanges();
return RedirectToAction("View", "Recipe", new { id = recipeid });
}
u<script type="text/javascript">
$("#Save").click(function () {
var ingredients = $("#ingredients tr.ingredientdata").map(function (element, index) {
return {
ingredientName: $("td.ingredient", this).text(),
units: $("td.units", this).text(),
measure: $("td.measure", this).text()
};
}).toArray();
var json = {
RecipeTitle: $("#recipetitle").val(),
CategoryID: $("#category").val(),
PrepTime: $("#prepTime").val(),
PrepTimePeriod: $("#lstPrepTime").val(),
CookTime: $("#cookTime").val(),
CookTimePeriod: $("#lstCookTime").val(),
Rating: $("#rating").val(),
Method: $("#method").val(),
Comment: $("#comment").val(),
AccessLevel: $("#accessLevel").val(),
Ingredients: ingredients
};
$.ajax({
url: "/Recipe/Save",
type: "POST",
dataType: 'json',
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
success: function () {
//alert("DONE!!");
}
});
});
[/code]
Malcolm

You need to send back the Url and redirect it from the client script.
success: function (urlData) {
window.location.href = urlData ;
return false;
}
or you may show an error message based on the response received.

Related

jQuery function not getting called in mvc text-changed event

I am getting this strange behavior in jQuery when working with mvc application.
Below is MVC view in which I have implemented Text change event,
#Html.TextBoxFor(m => m.UserId, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.UserId, "", new { #class = "text-danger" })
$("#UserId").change(function () {
var UserId = $(this).val();
//$("#txtName").val(emailId);
$.ajax({
url: 'GetValidUserName',
type: 'POST',
data: JSON.stringify({ UserId: UserId }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
if (!$.trim(data)) {
alert("User does not exist in system. Please enter valid User Id.");
$(':input[type="submit"]').prop('disabled', true);
}
else {
$("#UserId").val(data);
$("#UserId").focus();
$(':input[type="submit"]').prop('disabled', false);
}
}
});
});
While debugging application when I load Index view directly first time , jQuery function gets called and invoke the controller action properly.http://localhost:51012/UserApplication/Index
But when I load the view again, jQuery function doesn't get called.
Controller code,
public JsonResult GetValidUserName(string userId)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
string UserID = "";
objLMT.UserList = objLMTDAL.GetAll_User("", 0, "6");
var AllUsersInDatabase = from p in objLMT.UserList
where p.UserId == userId
select new
{
Name = p.UserName,
Id = p.UserId,
};
foreach (var user in AllUsersInDatabase)
{
if (user.Name != null)
{
UserID = user.Id;
}
}
return Json(UserID, JsonRequestBehavior.AllowGet);
}
You have several issues with AJAX callback:
1) type: 'POST' option requires [HttpPost] attribute. If the attribute isn't present on the action method, use type: 'GET' instead.
2) You don't need JSON.stringify() to pass single parameter containing simple types (numeric and string values). A simple { userId: UserId } should be fine.
3) The controller action's parameter name must be exactly match with parameter name sent from AJAX callback.
Therefore, your AJAX callback should be follow example below:
$(function () {
$("#UserId").change(function () {
var UserId = $(this).val();
$.ajax({
url: '#Url.Action("GetValidUserName", "ControllerName")',
type: 'GET',
data: { userId: UserId },
dataType: 'json',
success: function (data) {
if (!$.trim(data)) {
alert("User does not exist in system. Please enter valid User Id.");
$(':input[type="submit"]').prop('disabled', true);
}
else {
$("#UserId").val(data);
$("#UserId").focus();
$(':input[type="submit"]').prop('disabled', false);
}
}
});
});
});

Render View with Json Result

Im wondering is it possible to render a view from a json result, basically when the user clicks on a button in my view, i want to go and fetch data from my controller/model using json result, with this data i want to open a view with the new data, is this possible?
AJax Call
$.ajax({
type: 'POST',
url: '#Url.Action("GetAdminSubmissions", "Inspections")',
contentType: "application/json; charset=utf-8",
datatype: JSON,
data: { 'selectedDepartment': deparment, 'searchDate': selectedDate },
success: function (result) {
// on success open view with new updated model
},
error: function (result) {
alert(result);
}
});
}
Controller
public JsonResult GetAdminSubmissions(string selectedDepartment, string searchDate)
{
var result = new List<Checks_Records>();
if (searchDate != null)
{
var enUkCultureInfo = new CultureInfo("en-GB");
var userSelectedDate = DateTime.Today.Date.AddHours(7);
DateTime parsedDate;
if (DateTime.TryParseExact(searchDate, "dd-MMMM-yyyy", enUkCultureInfo, DateTimeStyles.None, out parsedDate))
{
userSelectedDate = parsedDate.AddHours(7);
result = Model.GetListofChecks_Records(userSelectedDate, selectedDepartment);
var json = new JavaScriptSerializer().Serialize(result);
return Json(json, JsonRequestBehavior.AllowGet);
}
}
return error;
}

Passing parameters in ajax call

I'm trying to make an ajax call to the controller method. without parameter it works fine. Once i add the parameter i always receive a null parameter to the cotroller. I think i have correctly done the parameter passing in ajax call.
<script type="text/javascript">
$(document).ready(function () {
$('#lstStock').change(function () {
var serviceURL = '<%= Url.Action("GetStockPrice", "Delivery") %>';
var dropDownID = $('select[id="lstStock"] option:selected').val();
alert(dropDownID); // here i get the correct selected ID
$.ajax({
type: "POST",
url: serviceURL,
data: '{"stockID":"' + dropDownID + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data.Result);
}
function errorFunc() {
alert('error');
}
})
});
</script>
Controller:
[HttpGet]
public ActionResult GetStockPrice()
{
return View();
}
[HttpPost]
[ActionName("GetStockPrice")]
public ActionResult GetStockPrice1(string stockID)//I get the null parameter here
{
DeliveryRepository rep = new DeliveryRepository();
var value = rep.GetStockPrice(stockID);
return Json(new { Result = value }, JsonRequestBehavior.AllowGet);
}
It's because you are treating the data as a string
data: '{"stockID":"' + dropDownID + '"}',
you can change it to:
data: { stockID: dropDownID },
in some cases, depending on the parameter declared in your controller method, you need to serialize the data. If you need to do that then this is how you would do it:
var o = { argName: some_value };
$.ajax({
// some other config goes here
data: JSON.stringify(o),
});
try data: { stockID : dropDownID},
$('#lstStock').change(function () {
var serviceURL = '<%= Url.Action("GetStockPrice", "Delivery") %>';
var dropDownID = $('select[id="lstStock"] option:selected').val();
// $(this).val(); is better
alert(dropDownID); // here i get the correct selected ID
$.ajax({
type: "POST",
url: serviceURL,
data: { stockID : dropDownID},
....
Try specifying:
data: { stockID : dropDownID },
It looks like you're passing up "stockID" not stockID.
A good tool to use for this is Fiddler, it will allow you to see if the Controller action is hit and what data was sent upto the server.

ASP.Net MVC Get ID of newly added record from AJAX post

How do I retrieve the ID from the following model, after the following JQuery/Ajax posts to it:
JQuery:
$.ajax({
type: 'POST',
url: '/api/searchapi/Post',
contentType: 'application/json; charset=utf-8',
data: toSend,
}).done(function (msg) {
alert( "Data Saved: " + msg );
});
Controller:
// POST api/searchapi
public Void Post(Booking booking)
{
if (ModelState.IsValid)
{
tblCustomerBooking cust = new tblCustomerBooking();
cust.customer_email = booking.Email;
cust.customer_name = booking.Name;
cust.customer_tel = booking.Tel;
bc.tblCustomerBookings.Add(cust);
bc.SaveChanges();
long ID = cust.customer_id;
Return ID; <-- what do I enter here?
}
Return "Error"; <-- and here?
}
How can I get the ID back into the jQuery script, and if the model isn't valid, how do I return an error to the jQuery?
Thanks for any help,
Mark
You could return a JsonResult
[HttpPost]
public ActionResult Post(Booking booking)
{
if (ModelState.IsValid)
{
tblCustomerBooking cust = new tblCustomerBooking();
cust.customer_email = booking.Email;
cust.customer_name = booking.Name;
cust.customer_tel = booking.Tel;
bc.tblCustomerBookings.Add(cust);
bc.SaveChanges();
return Json(new { id = cust.customer_id });
}
return HttpNotFound();
}
and then on the client simply:
$.ajax({
type: 'POST',
url: '/api/searchapi/Post',
contentType: 'application/json; charset=utf-8',
data: toSend,
}).done(function (msg) {
alert('Customer id: ' + msg.id);
}).error(function(){
// do something if the request failed
});
One way to do it is like this:
In your controller:
public Void Post(Booking booking)
{
//if valid
return Json(new {Success = true, Id = 5}); //5 as an example
// if there's an error
return Json(new {Success = false, Message = "your error message"}); //5 as an example
}
In your ajax post:
$.ajax({
type: 'POST',
url: '/api/searchapi/Post',
contentType: 'application/json; charset=utf-8',
data: toSend,
success: function(result) {
if (result.Success) {
alert(result.Id);
}
else {
alert(result.Message);
}
}
});
returning void isn't a good idea, use JsonResult
Because you are using JavaScript, I recommend using JSON.
return this.Json(new { customerId = cust.customer_id});
In order to receive a return value, the controller method must return something other than void.
Does your controller compile? Your post method has a void return type, so it should fail compilation when it sees the return ID and return "Error" commands

Redirect from Webmethod in Asp.Net

Am new to Asp.Net Programming, Have just started a web project.
Am calling a WebMethod from Aspx page using JSON like below:
<script type="text/javascript">
function getLogin() {
var userName = document.getElementById('TextBox1').value;
$.ajax({
type: "POST",
url: "Services/LogService.asmx/authenticateLogin",
data: "{'userName':'" +userName.toString()+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d)
},
error: function (xhr, status, error) {
// alert(textStatus);
DisplayError(xhr);
}
});
}
function DisplayError(xhr) {
var msg = JSON.parse(xhr.responseText);
alert(msg.Message); }
</script>
And WebMethod :
[WebMethod]
public string authenticateLogin(string userName)
{
LoginBO loginBO = new LoginBO();
loginBO.userName = userName.ToString().Trim();
string result = "";
try
{
LoginDao loginDao = DAOFactory.GetDaoFactory().getLoginDao();
result = loginDao.selectUser(loginBO);
}
catch (DBConnectionException)
{
//result = "DB Conenction";
throw new Exception("DB Connection is Down");
}
catch (InvalidLoginException)
{
//HttpResponse res = new HttpResponse();
//HttpResponse.ReferenceEquals.Redirect("~/Login.aspx");
throw new InvalidLoginException("Login Is Invalid");
}
catch (Exception)
{
throw new Exception("Uanble to Fetch ");
}
int ctx = Context.Response.StatusCode;
return result;
}
After Successful Authentication, I want to redirect user to another aspx page.
What is the best practice to do ?
Thanks
Samuel
Add a redirect to the success section of your getLogin() function:
success:
function (response) {
alert(response.d);
windows.location.href = "http://url.for.redirect";
}
(Or use some other method for redirecting within jQuery/Javascript).
In your Ajax method
success: function(msg) {
alert(response.d);
window.location = "xyz.aspx";
},
success: function (response) {
alert(response.d)
window.location.href = "some.aspx";.
}
I think it will help you.

Resources