want to display selected item price in mvc - asp.net-mvc-4

My java script function
<script type="text/javascript">
$(document).ready (function(){
$(".dropdown").change(function () {
var name = $(".dropdown").val();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "#Url.Action("selectprice", "Stock")" + "?name=" + $(".dropdown").val(),
data: name,
success: function () { console.log("Good"); },
error: function () { console.log("Errrr"); }
});;
});
});
</script>
This is my controller to retrieve the price
[HttpPost]
public ActionResult selectprice(string name)
{
PharmaDB db = new PharmaDB();
ViewData["price"] = db.drugs.Where(d => d.DRUG_ID == name).ToString();
return RedirectToAction("Edit");
}
now plz check is this correct or not,and how to display the retrive price in view

Change your controller code to this
[HttpPost]
public ActionResult selectprice(string name)
{
PharmaDB db = new PharmaDB();
var price = db.drugs.Where(d => d.DRUG_ID == name).ToString();
return Json(price, JsonRequestBehavior.AllowGet);
}
And change your ajax success function to this
success: function (data) { console.log(data); }
In console your selected price will be displayed.

Related

ASP.NET Core MVC : HTTP POST method not return to view

View:
#Html.DropDownList("bolumler", null, "lutfen bolum secin",
new {#class = "form-control",
#onchange="SelectedIndexChanged(this)"})
<script type="text/javascript">
function SelectedIndexChanged(item) {
var value = item.value;
$.ajax({
type: "POST",
url: "#Url.Action("GoTo")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data:JSON.stringify( value ),
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
Controller:
[HttpPost]
public async Task<IActionResult> GoTo([FromBody] string d)
{
var personeller = await _iluPersonelService.getPersonelWithDepartment(d);
List<SelectListItem> valuesForPersonel = (from x in personeller
select new SelectListItem
{
Text = x.Name,
}).ToList();
ViewBag.personeller = valuesForPersonel;
return View();
}
I can't figure out this problem. In .cshtml side, I change dropdownlist selection item and controller post method triggering. I did some operations on the data and I want to return new data to view and display it.
Note: there are no changes on the page and it is not refreshed
Do you want to alert(data) ?
If so , do you want the below way ?
change the action like below:
[HttpPost]
public async Task<IActionResult> GoTo([FromBody] string d)
{
...
return Json(valuesForPersonel);
}
public IActionResult Goto()
{
return View();
}
2.In the view:
change the success method code in your ajax:
$.ajax({
type: "POST",
url: "#Url.Action("GoTo")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(value),
success: function (data) {
for (var i = 0; i < data.length; i++) {
alert(data[i].text);
window.location.href = "https://localhost:7169/RtCd/Goto";
}},
failure: function (errMsg) {
alert(errMsg);
}
});
result:

ASP.NET Core AJAX POST not returning error, however, not saving data

I am using a button OnClick event to try and save a record to a database using AJAX in ASP.NET Core. The function is not returning an error, however, the data is not being saved. I am just trying to test with hard coded data first. A record with AdapollingProjectProcessStatusId = 1 exists in the database.
function SendHtmlEditorValueToController(data) {
$.ajax({
type: 'POST',
url: '#Url.Action("AJAXPost", "LiveAdapollingProjectProcessStatus")',
contentType: "application/json",
data: JSON.stringify({ "id": 1, "status": 'test'}),
dataType: 'json',
success: () => {
console.log("value is sent");
},
error: (error) => {
console.log(JSON.stringify(error));
}
});
}
LiveAdapollingProjectProcessStatusController:
[HttpPost]
public JsonResult AJAXPost(int id, string status)
{
LiveAdapollingProjectProcessStatus processstatus = new LiveAdapollingProjectProcessStatus
{
AdapollingProjectProcessStatusId = id,
AdapollingProjectProcessStatus = status
};
//save it in database
return Json(processstatus);
}
LiveAdapollingProjectProcessStatus.cs:
namespace CPSPMO.Models.PMO
{
public partial class LiveAdapollingProjectProcessStatus
{
public int AdapollingProjectProcessStatusId { get; set; }
public string AdapollingProjectProcessStatus { get; set; }
}
}
Please let me know if you are able to help me with this AJAX Post.
Thanks
Not sure how do you store it to the database, but the way you pass parameter to backend by ajax should be like below:
function SendHtmlEditorValueToController(data) {
$.ajax({
type: 'POST',
url: '#Url.Action("AJAXPost", "LiveAdapollingProjectProcessStatus")',
//contentType: "application/json", //remove this...
data:{ "id": 1, "status": 'test'}, //modify here...
dataType: 'json',
success: () => {
console.log("value is sent");
},
error: (error) => {
console.log(JSON.stringify(error));
}
});
}
After reviewing the comments regarding missing code for saving the data in the database, I modified the controller:
[HttpPost]
public JsonResult AJAXPost(int id, string status)
{
LiveAdapollingProjectProcessStatus processstatus = new LiveAdapollingProjectProcessStatus
{
AdapollingProjectProcessStatusId = id,
AdapollingProjectProcessStatus = status
};
//save it in database
var result = _context.LiveAdapollingProjectProcessStatuses.Update(processstatus);
_context.SaveChanges();
return Json(processstatus);
}
It is saving the data to the database now. Thanks for the help

Can not pass list of object to method by AJAX

I'm sorry that this question has been too long. I have consulted a lot of articles on Stack Overflow but it doesn't run on my source code. I am using ASP.NET Core MVC.
My AJAX
function PayAjax(orders, payment, note) {
orders = [{ 'id': 1, 'quantity': 2 }, { 'id': 3, 'quantity': 4 }];
var formData = new FormData();
formData.append('orders', orders);
formData.append('payment', payment);
formData.append('note', note);
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/sale/pay',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (result) {
var x = 1;
},
error: function (error) {
console.log(error);
}
});
}
My controller
[HttpPost]
public async Task<IActionResult> Pay(List<Order> orders, int payment, string note)
{
...
}
}
My Object Order
public class Order
{
public int Id { get; set; }
public int Quantity { set; get; }
}
My data is coming to controller but I don't access to values.
Orders always have count = 0.
Even if I pass JSON like below, controller orders is always empty
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/sale/pay',
type: 'POST',
data: JSON.stringify({ 'orders': orders, 'payment': payment, 'note': note}),
processData: false,
contentType: false,
success: function (result) {
var x = 1;
},
error: function (error) {
console.log(error);
}
});
Try to put data into formData one by one:
function PayAjax(orders, payment, note) {
orders = [{ 'id': 1, 'quantity': 2 }, { 'id': 3, 'quantity': 4 }];
var formData = new FormData();
for (var i = 0; i < orders.length; i++) {
formData.append("orders[" + i + "].Id", orders[i].id);
formData.append("orders[" + i + "].Quantity", orders[i].quantity);
}
formData.append('payment', payment);
formData.append('note', note);
$.ajax({
dataType: 'json',
url: '/sale/pay',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (result) {
var x = 1;
},
error: function (error) {
console.log(error);
}
});
}
You can wrap these parameter request to single object
[HttpPost]
public async Task<IActionResult> Pay(PayRequest request)
public class PayRequest
{
public List<Order> orders {get; set;}
public int payment {get; set;}
public string noteget; set;}
}
you should get parameters by [FromForm] annotation and convert object to FormData if you want post it using formData
public ActionResult Pay([FromForm] List<Order> orders, [FromForm] int payment, [FromForm] string note) {
}
function buildFormData(formData, data, parentKey) {
if (data && typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
Object.keys(data).forEach(key => {
buildFormData(formData, data[key], parentKey ? `${parentKey}[${key}]` : key);
});
} else {
const value = data == null ? '' : data;
formData.append(parentKey, value);
}
}
function jsonToFormData(data) {
const formData = new FormData();
buildFormData(formData, data);
return formData;
}
function pay() {
orders = [{ 'Id': 1, 'Quantity': 2 }, { 'Id': 3, 'Quantity': 4 }];
PayAjax(orders, 2000, 'Hello')
}
function PayAjax(orders, payment, note) {
const dataToSend = {
orders,
payment,
note
}
const data = jsonToFormData(dataToSend)
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/sale/pay',
type: 'POST',
data,
processData: false,
contentType: false,
success: function (result) {
var x = 1;
},
error: function (error) {
console.log(error);
}
});
}

ViewModel is going null in Controller when data is posting through ajax

I am posting the data through ajax from my form but it is going null always.
What i am doing is:-
In my View Page:-
<script>
$(document).ready(function () {
$("#blogForm").submit(function (e) {
e.preventDefault();
alert("YOO");
debugger;
var fileInput = $('#authorImage')[0];
var authorImage = fileInput.files[0];
//var blogFile = $("#blogImages")[0];
//var blogImages = blogFile.files[0];
var editor = new Quill('#editor');
var content = editor.getContents();
var BlogData =
{
Title: $(".txttitle").val(),
DestinationId: $("#ddlDesignation").val(),
Category: $("#ddlCategory").val(),
Author: $(".txtauthor").val(),
AuthorDetail: $(".txtauthorDetail").val(),
Date: $(".txtDate").val(),
Contents: content
}
var CreateEditBlogsViewModel =
{
BlogDTO: BlogData
}
var param = JSON.stringify(CreateEditBlogsViewModel);
//doing ajax request
$.ajax({
contentType: "application/json",
method: "POST",
dataType:"JSON",
url: "#Url.Action("Create", "Blog")",
data: param,
success: function () {
alert("success");
},
error: function () {
alert("Error");
}
});
});
});
</script>
In my Controller:
[HttpPost]
public IActionResult Create(CreateEditBlogsViewModel BlogDTO,IFormFile authorimage,IFormFile images)
{
if (ModelState.IsValid)
{
_blogservice.Insert(BlogDTO.BlogDTO);
}
//rebinding values
BlogDTO.DestinationSelectList = GetDestinationSelectList();
BlogDTO.BlogCategorySelectList = GetBlogCategorySelectList();
return View();
}
My Model looks like this:
public class CreateEditBlogsViewModel
{
public BlogsDTO BlogDTO { get; set; }
public List<SelectListItem> DestinationSelectList { get; set; }
public List<SelectListItem> BlogCategorySelectList { get; set; }
}
I have also tried applying [FromBody] in controller,but no luck. I also have to post 2 seperate images also but at first i only want that data then i will try to post image.
Please Help.
Edit : I have solved this by using CKEditor in place of quill editor and now I am posting all the data using form.

how to call this calling WCF method continuously

I have an ajax enabled WCF service method :
[OperationContract]
public string Test(string name)
{ return "testing testing." + name; }
and I am calling it with following code:
$(document).ready(function () {
var varData = $("#NewSkill").val();
$("#Button1").click(function () {
$.ajax({
type: "POST",
url: "TimeService.svc/Test",
data: '{"name" : "John"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
});
});
I want to call this method continuously after every 5 seconds using above code . How can I do this ?
Move the $.ajax(); part to a Javascript function say AjaxCall(). Create a javascript variable
var isActivated = false;
$(document).ready(function () {
while(isActivated){
setTimeout("AjaxCall()",3000);
}
}
);
$("#Button1").click(isActivated = true)
Hope this helsps...