Render View with Json Result - asp.net

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;
}

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);
}
}
});
});
});

AJAX data parse to Controller and return back

Here is an AJAX call to the controller:
$.ajax({
type: "GET",
url: '#Url.Action("getChat", "Chat")',
success: function (data) {
alert(data);
$("#data").html(data);
},
error:{
}
});
In the controller code, I have a database query which returns multiple rows.
I want to return that variable back to JSON and print each row separately in AJAX and write that data in HTML.
Here is my Controller code
public ActionResult getChat()
{
var p = (from v in DB.chats where v.chatuserID == id select new { v.status, v.message }).ToList();
return Content(p.ToString());
}
The query is returning data. I am attaching an image that shows the variables content.
public JsonResult getChat()
{
var p = (from v in DB.chats
where v.chatuserID == id select new { v.status,
v.message
}).ToList();
return json(p,JsonRequestBehavior.AllowGet);
}
Now you can loop through the list in you ajax success callback function : here is stuff.
$.ajax({
type: "GET",
url: '#Url.Action("getChat", "Chat")',
success: function (data) {
$.each(data,function(){
console.log("Status "+ data.status +" "+"Message"+ data.message);
});
},
error:{
}
});

How can I call controller post action from jquery (in custom view page) in mvc .net web app

I am creating a web application for event management using .net mvc and jquery.
I created a mvc web app.contoller named SeatPlansController and model named SeatPlanes and I am able to insert the data to database.
But I am not able pass the data from jquery to database using the mvc controller.
My controller action code is as shown below
// GET: SeatPlans/Create
public ActionResult Create()
{
return View();
}
// POST: SeatPlans/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(String seat_id, String seat_no)
{
int id = 10;
SeatPlans S = new SeatPlans();
S.seat_id = seat_id;
S.seat_no = seat_no;
if (ModelState.IsValid)
{
db.SEATPLAN.Add(S);
db.SaveChanges();
// return RedirectToAction("Index");
}
return View(S);
}
In post create controller Id is primary key, so I want to pass seat_id,seat_no as argument and it should update the database.
I used following javascript
function getPerson(id) {
$.ajax({
type: "GET",
url: '#Url.Action("create", "SeatPlanesController")',
contentType: "application/json; charset=utf-8",
data: {eat_id :6, seat_no:8},
dataType: "json",
success: function (result) {
alert(result);
//window.locationre = result.url;
}
});
}
I am able to run the create get method using
http://localhost:52348/SeatPlans/Create
but how can I run post method directly from browser with argument
something like
http://localhost:52348/SeatPlans/Create/2/3t/e
I have changed the script as bellow,it works for GET method but if i made TYPE:"post" it popup an alert box with alert
"localhost:52348 says:
internal server error"
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Create", "SeatPlans", new { Area = "" })',
data: { seat_id: "34", seat_no: "98" },
dataType: "json",
async: false,
success: function (result) {
$("#div1").html(result);
},
error: function (abc) {
alert(abc.statusText);
},
});
});
});
Finally i got the sollution
i changed the script as bellow
//jQuery.noConflict();
// var $j = jQuery.noConflict();
function clickevent()
{
var form = $("#frm");
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
type: "post",
// headers: { "__RequestVerificationToken": token },
url: '#Url.Action("Create", "SeatPlans")',
data: {
seat_id: "34", seat_no: "98"
},
success: function (result) {
$("#div1").html(result);
}
});
}
and change the create post method as bellow
<pre>
public ActionResult Create(String seat_id, String seat_no)
{
int id = 10;
SeatPlans S = new SeatPlans();
S.seat_id = seat_id;
S.seat_no = seat_no;
if (ModelState.IsValid)
{
db.SEATPLAN.Add(S);
db.SaveChanges();
// return RedirectToAction("Index");
}
return View(S);
}

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

How to handle $.ajax

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.

Resources