asp.net MVC return json - c#

I use $http request to call MVC controller and return data in JSON format. But i not able to get the result in javascript/angualr js. It return entire HTML page. Where i made the mistake?
myapp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.toggle = function () {
$http({
url: "/Admin/FilterMember",
method: "GET",
params: { id: $('#txtsearch').val() }
}).then(function (result) {
alert(result);
});
};
}]);
Above is angular script in JS file.
public ActionResult FilterMember(string id)
{
SqlParameter[] SqlParam = { new SqlParameter("#Filter", id) };
DataTable dTable = MasterMindDB.dTableSP(DbConn, "SP_Get_MemberList", SqlParam);
List<Member> member = new List<Member>();
foreach (DataRow row in dTable.Rows)
{
member.Add(new Member
{
MemberName = row["Member ID"].ToString(),
Email = row["Email"].ToString(),
JoinDate = row["Join Date"].ToString(),
Status = row["Status"].ToString()
});
}
return View("Member", Json(member, JsonRequestBehavior.AllowGet));
}
Above is MVC controller

This action is for the FilerMember view
[HttpGet]
public ActionResult FilterMember () {
return View();
}
This action will be called from the client side view. No need to return a ViewResult, just the data
[HttpGet]
public ActionResult GetMemberById(string id) {
SqlParameter[] SqlParam = { new SqlParameter("#Filter", id) };
DataTable dTable = MasterMindDB.dTableSP(DbConn, "SP_Get_MemberList", SqlParam);
List<Member> member = new List<Member>();
foreach (DataRow row in dTable.Rows) {
member.Add(new Member {
MemberName = row["Member ID"].ToString(),
Email = row["Email"].ToString(),
JoinDate = row["Join Date"].ToString(),
Status = row["Status"].ToString()
});
}
//Just return JsonResult.
return Json(member, JsonRequestBehavior.AllowGet);
}
Updated client
myapp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.toggle = function () {
$http({
url: "/Admin/GetMemberById",
method: "GET",
params: { id: $('#txtsearch').val() }
}).then(function (result) {
alert(result);
});
};
}]);

Related

Ajax call to controller results in 400 error

I have the follow Ajax call that points to a controller function:
<script type="text/javascript">
$(document).ready(function () {
$('#AddNote').click(function () {
$('#AddNote').addClass("disabled");
var txtNote = document.getElementById('note');
var result = document.getElementById('result');
result.innerText = "Adding note...";
$.ajax({
url: "#Url.Action("AddNoteAsync", "Leads")",
type: "POST",
data: { leadId: #Model.Id, note: txtNote.value },
async: true,
success: function (data) {
// removed
},
});
});
});
</script>
When I click the AddNote button I see the "Adding note..." message display and then nothing else happens. When I check the console in chrome, it reads:
:44309/Leads/AddNoteAsync:1 - Failed to load resource: the server responded with a status of 400 ()
So I know 400 means bad request but I'm not sure why it's happening. I've tried:
Added quotes to the "leadId" and "note" field in data - made no difference.
Added alert boxes to show the value of #Model.Id and txtNote.value before the AJAX call to verify they are correct - they are.
Put a breakpoint in the AddNoteAsync function in my controller - it's never hit
Hard coded the url field to /Leads/AddNoteAsync - made no difference
Since the controller function is never being hit I'm assuming something is wrong with the &.ajax part but I cannot figure out what.
Edit: The controller method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddNoteAsync(int? leadId, string note)
{
ViewData["AddedNote"] = false;
if (leadId == null)
{
return RedirectToAction("Index", new { initials = User.Identity.Name });
}
var lead = await _context.Leads.FirstOrDefaultAsync(m => m.Id == leadId);
if (lead == null)
{
return RedirectToAction("Index", new { initials = User.Identity.Name });
}
var ownsLead = await LeadBelongsToCurrentUser(leadId.Value, User.Identity.Name);
if (!ownsLead)
{
return RedirectToAction("Index", new { initials = User.Identity.Name });
}
_context.LeadNotes.Add(new LeadNoteModel()
{
LeadId = leadId.Value,
Note = note,
NoteDate = DateTime.Now
});
await _context.SaveChangesAsync();
ViewData["AddedNote"] = true;
return Content("Success");
}
You should accept parameters as Model while making POST request(Recommended). Proposed Model will be -
public class NoteModel
{
public int? leadId { get; set; }
public string note { get; set; }
}
and Action can be -
public async Task<IActionResult> AddNoteAsync(NoteModel model)
{
}
Also Jquery can be -
<script type="text/javascript">
$(document).ready(function () {
$('#AddNote').click(function () {
$('#AddNote').addClass("disabled");
var txtNote = document.getElementById('note');
var result = document.getElementById('result');
var postData = { leadId: #Model.Id, note: txtNote.value };
result.innerText = "Adding note...";
$.ajax({
url: "#Url.Action("AddNoteAsync", "Leads")",
type: "POST",
data: JSON.stringify(postData),
async: true,
success: function (data) {
// removed
},
});
});
});
Fixed this. I was missing this from my AJAX request:
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="f"]').val());
},
And this from my Startup.cs:
services.AddAntiforgery(options =>
{
options.FormFieldName = "f";
options.HeaderName = "XSRF-TOKEN";
});

How do I delete from the database in Asp.Net Core via Ajax?

This script is supposed to send a ProductId to the home controller's Delete-method, and the controller should make the appropriate Remove-operation:
$('[name="DeleteItem"]').click(function (e) {
$.ajax({
type: "DELETE",
url: "#Url.Action('Delete','Home')",
data: { id: $('DeleteItem#data-id').val() },
success: function () {
alert("success!");
window.location.replace("#Url.Action('Index', 'Home')");
},
error: function (data) {
alert("Error: " + data.id);
}
});
});
This is the form:
<form asp-action="Update">
#foreach (var item in Model.ShoppingCartItems)
{
#item.ProductTitle
<input asp-for="#item.Quantity" />
<button name="DeleteItem" data-id="#item.ProductId">DELETE</button>
}
<button type="submit">Update quantity</button>
</form>
This is the controller's Delete-method (I don't have the ShoppingCartId, so I'm getting it based on SessionId, which is stored in the ShoppingCarts-table):
[HttpDelete]
//[ValidateAntiForgeryToken] // <-- Do I need this in this case?
public async Task<IActionResult> Delete(
[Bind("ShoppingCartItemProductId")]
ViewModelAddToCart model)
{
// Initialize session to enable SessionId
HttpContext.Session.SetString("_Name", "MyStore");
string SessionId = HttpContext.Session.Id;
var ShoppingCart = new ShoppingCart()
{
SessionId = SessionId
};
var ShoppingCartItem = new ShoppingCartItem()
{
ProductId = model.ShoppingCartItemProductId,
};
if (ModelState.IsValid)
{
// Find ShoppingCart containing current SessionId.
var cartInfo =
(from Cart in _context.ShoppingCarts
where Cart.SessionId == SessionId
select new { TempId = Cart.Id })
.SingleOrDefault();
if (cartInfo != null)
{
ShoppingCartItem.ShoppingCartId = cartInfo.TempId;
}
// Find ShoppingCartItem containing current ProductId:
var cartItemInfo =
(from CartItem in _context.ShoppingCartItems
where (CartItem.ShoppingCartId == ShoppingCartItem.ShoppingCartId &&
CartItem.ProductId == model.ShoppingCartItemProductId)
select new { TempId = CartItem.Id })
.FirstOrDefault();
if (cartItemInfo != null)
{
// Delete ShoppingCartItem
ShoppingCartItem.Id = cartItemInfo.TempId;
_context.ShoppingCartItems.Remove(ShoppingCartItem);
}
await _context.SaveChangesAsync();
return RedirectToAction("Index", "Home");
}
else
{
return View("Index", "Home");
}
}
Edit I have made some changes to my code, and now I receive "Error: undefined" in an alert. That is because the error: in the ajax is triggered, and the data-object is not defined. Why is that? And a second question is what is the controller supposed to return? As I understand, not a RedirectToAction.
what is "deleteitem"
you should have some id or class for the button in your case class should be easy
<button name="DeleteItem" class = "deleteitemevent" data-id="#item.ProductId">DELETE</button>
$(".deleteitemevent").click(function (e) {
}
[HttpPost]
[ValidateAntiForgeryToken]
//^^yes you should for any post... but since you insist on
//doing ajax calls...
//you will have to research how to build this up... from JS and inject with the ajax call..
public async Task<IActionResult> Delete(
[Bind("ShoppingCartItemProductId")]
ViewModelAddToCart model)
{
//...
}
$('[name="DeleteItem"]').click(function (e) {
var dataid = $(this).attr('data-id'); // because name was used for control not id
$.ajax({
type: "POST",
url: "#Url.Action('Delete','Home')",
data: { id: dataid },
success: function () {
alert("success!");
window.location.replace("#Url.Action('Index', 'Home')");
},
error: function (data) {
alert("Error: " + data.id);
}
});
});
I think you have a long way to go... There are easier ways of doing this without needing ajax calls...

How to return MVC view to JQuery post success delegate

I have the following JQuery method for posting data to a action in my MVC contorller:
$('#btnAddNewTest').on("click", function () {
var date = $('#HIVTestTestDate').val();
var result = $('#HIVTestTestResult').val();
var cd4 = $('#HIVTestCD4Count').val();
var pID = $('#PatientID').val();
var dataToSend = { patientID: pID, testDate: date, resultID: result, cd4Count: cd4 };
$.post("/HIVInformation/AddHIVTest/", dataToSend, function (receivedData) {
location.reload(false); //Don't want to do this
});
return false;
});
Here is the Action method in my controller:
[HttpPost]
public ActionResult AddHIVTest(Guid patientID, DateTime testDate, Guid resultID, int cd4Count)
{
MvcPatientDetailsHIVViewModel model = new MvcPatientDetailsHIVViewModel(patientID);
model.LoadAllData();
try
{
//add the HIV Test
model.HIVTestResult = new Common.Models.PatientHIVTestModel()
{
ID = Guid.NewGuid(),
PatientID = patientID,
TestDate = testDate,
HIVTestResultID = resultID,
CD4Count = cd4Count
};
//call the add method
model.AddHIVTestResults();
}
catch (Exception ex)
{
ModelState.AddModelError("", ex);
}
return View("Details", model);
}
If I comment out the 'location.reload(false);' my page does not get refreshed. How do I serialize my Mvc view to be returned in the function (receivedData) delegate of the post? How do I display my view then from within the JQuery code?
if i may, i would suggest to you to use ajax, partial views, and a container div for example to load the result in it.
Example:
Script:
$(document).ready(function () {
$("#btnAddNewTest").on("click", function () {
$.ajax({
url: '#Url.Action("YourAction", "YourController")',
type: 'post',
data: {
yourData1: value1,
yourData2: value2,
},
success: function (result) {
$('#dynamicContent').html(result);
}
});
});
});
Controller:
public ActionResult YourAction(int yourData1= 1, int yourData2 = 0)
{
return PartialView("~/yourviewPath/_YourPartialView.cshtml", yourResultModel)
}
Html:
<div id="dynamicContent" class="Float_Clear">
#Html.Partial("~/yourviewPath/_YourPartialView.cshtml", Model)
</div>
Live example that I created using the same concept here

500 Internal Server Error JsonResult mvc asp.net

trying to create a cascading dropdownmenu with jsonresult and ajax, but i cant see why am i getting 500 Internal Server Error. The error occurs above the following method :
[HttpGet]
public JsonResult GetModels(string brandID="")
{
List<Model> models = new List<Model>();
int ID = 0;
if (int.TryParse(brandID, out ID))
{
using (CarsEntities1 dc = new CarsEntities1())
{
models = dc.Models.Where(a => a.Brand_ID == ID).OrderBy(a =>a.Model_name).ToList();
}
}
if (Request.IsAjaxRequest())
{
return new JsonResult
{
Data = models,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
return new JsonResult
{
Data = "Not valid request",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
I use the method to pass a list of items into DropDownMenu and try to output the list by the following code :
$(document).ready(function () {
//if (typeof ($) == 'function') alert('jQuery is loaded.');
$("#brand_Brand_ID").change(function () {
// this will call when Brand Dropdown select change
var brandID = parseInt($("#brand_Brand_ID").val());
if (!isNaN(brandID)) {
var ddModel = $("#Model_ID");
ddModel.empty(); // this line is for clear all items from Model dropdown
ddModel.append($("<option></option").val("").html("Select model"));
// Here I will call Controller Action via Jquery to load Model for selected Brand
$.ajax({
url: "#Url.Action("GetModels","ModelSpec")",
type: "GET",
data: { brandID: brandID },
dataType: "json",
success: function (data) {
if (data != null && data.success) {
$.each(data, function (i, val) {
ddModel.append(
$("<option></option>").val(val.Model_ID).html(val.Model_name)
);
});
}
},
error: function () {
alert("Fail");
}
});
}
});
});
All i get is the following :
GET http://localhost:2508/ModelSpec/GetModels?brandID=2 500 Internal Server Error jquery-1.7.1.js (line 8102)
Also i noticed the error doesnt occur when theres no data passing through the GetModels method. And sometimes i get :
GET /ModelSpec/GetModels?brandID=5 401 Unauthorized
As soon as GetModels returns anything the error occurs else not.
The ObjectContext instance has been disposed and can no longer be used for
operations that require a connection
Stacktrace :
http://pastebin.com/3aXg7YiM
You need to move your return statements inside the using block
The Db context is disposed before you return statement is executed
public JsonResult GetModels(int brandID)
{
List<Model> models = new List<Model>();
using (CarsEntities1 dc = new CarsEntities1())
{
models = dc.Models.Where(a => a.Brand_ID == brandID).OrderBy(a =>a.Model_name);
if (Request.IsAjaxRequest())
{
return new JsonResult
{
Data = models.ToList(),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
return new JsonResult
{
Data = "Not valid request",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
json return type has to be primitive, so i changed the code accordingly(swap List to String[] and OrderBy to Select:
public JsonResult GetModels(int brandID)
{
String[] models;
using (CarsEntities1 dc = new CarsEntities1())
{
models = dc.Models.Where(a => a.Brand_ID == brandID).Select(a=> a.Model_name).toArray();
if (Request.IsAjaxRequest())
{
return new JsonResult
{
Data = models,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
return new JsonResult
{
Data = "Not valid request",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}

Angularjs Web Api Multpli Post action

I am beginner in Angularjs I want to have in my web api controller two post methods: one for registration and one for login. Here is my web api controller post methods:
//[EnableCors(origins: "*", headers: "*", methods: "*")]
// [ActionName("register")]
// [HttpPost]
public HttpResponseMessage PostRegister(Users Student)
{
if (ModelState.IsValid)
{
Random rnd = new Random();
int card = rnd.Next(52);
Student.user_id = card;
// _usertManager.AddUser(Student);
var activateToken = WebSecurity.CreateUserAndAccount(Student.user_mail, Student.password, Student);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, Student);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = Student.user_id }));
// _mailManager.Sendmail("salah.rzzaz90#gmail.com", "salahsayedrzzaz#gmail.com","dd","dd");
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
////[EnableCors(origins: "*", headers: "*", methods: "*")]
//[ActionName("Login")]
//[HttpPost]
public HttpResponseMessage PostLogin(string userMaill, string passwordd)
{
if (ModelState.IsValid)
{
_usertManager.Login(userMaill, passwordd);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, userMaill);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { userMaill = userMaill }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
my angular service :
this.post = function (Users) {
var request = $http({
method: "post",
url: "/api/HomeApi",
data:Users
});
return request;
}
this.post = function (userMaill, passwordd) {
var request = $http({
method: "post",
url: "/api/HomeApi",
data: { userMaill: userMaill, passwordd: passwordd }
});
return request;
}`
my angular controller :
$scope.save = function () {
var Users = {
user_id: $scope.user_id,
user_mail: $scope.user_mail,
fullname: $scope.fullname,
mobile: $scope.mobile,
secondmail: $scope.secondmail,
password: $scope.password,
type: $scope.type
};
var promisePost = CRUD_OperService.post(Users);
promisePost.then(function (pl) {
$scope.user_id = pl.data.user_id;
GetAllRecords();
$scope.Message = "Student Updated Successfuly";
ClearModels();
}, function (err) {
console.log("Err" + err);
});
};
$scope.login = function () {
var userMaill = $scope.userMaill;
var passwordd = $scope.passwordd;
var promisePost = CRUD_OperService.put(userMaill, passwordd);
promisePost.then(function (pl) {
$scope.user_id = pl.data.user_id;
GetAllRecords();
$scope.Message = "done";
ClearModels();
}, function (err) {
console.log("Err" + err);
});
};
My problem is that when I click register and login scope it calls PostRegister.

Categories

Resources