ViewModel is going null in Controller when data is posting through ajax - asp.net-core

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.

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

How To upload file from React Native to ASP.NET Core WebAPI

I want to upload an image file from react native to my server
React native code:
uploadData = () => {
let formdata = new FormData();
formdata.append('PhotoFile', {
uri: this.state.image,
type: 'image/png',
name: 'photo'
});
formdata.append('Title', this.state.title);
fetch('https://link/api/memes',{
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formdata
}).then(response => {
alert(response.status);
}).catch(err => {
alert(err);
});
}
I am using expo-image-picker to pick an image, and i store it in state
My Controller has a following prototype:
[HttpPost]
public async Task<IActionResult> CreateTitle([FromForm] TitleCreateDto titleCreateDto)
TitleCreateDto class lookes like this:
public class TitleCreateDto
{
public TitleCreateDto()
{
DateAdded = DateTime.Now;
}
public string Title { get; set; }
public DateTime DateAdded { get; set; }
public IFormFile PhotoFile { get; set; }
}

How do I send the JavaScript Array to the Controller from Ajax

Cannot get object values in the controller from the ajax post.
I have a jQuery data table with the first column being checkbox's and I need to return the selected row ids to the controller. I can get everything I need but it is always null in the controller.
Model:
public class Values
{
public Guid ID { get; set; }
}
View JS & Ajax on button click:
function SubAll() {
var values = [];
$('#timesheet').find('input[type="checkbox"]:checked').each(function (index, rowId) {
//this is the current checkbox
var temp = $(this).closest('tr').attr('id');
if (String(temp) === String("undefined")) {
//skip; it is the select all box
}
else {
//push to array
values.push(temp);
}
});
console.log(values);
var data = { ID: values };
console.log(data);
$.ajax({
url: "#Url.Action("ApproveAllTimesheets", "Admin")",
type: 'POST',
data: JSON.stringify(data),
dataType: 'json',
success: function (result) {
alert(result);
},
error: function (xhr, textStatus) {
if (xhr.status == 401) { alert("Session Expired!"); window.location = "/Account"; }
else {
alert('Content load failed!', "info");
}
}
});
};
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public void ApproveAllTimesheets(List<Values> value)
{}
On button click the array 'values' gets filled with the id if a box was selected (works fine), then it is turned into an object 'data' to match the method signature and model and stringify'd. When the breakpoint is hit on the controller method the values are never there. What am I missing?
**UPDATE:**
function SubAll() {
var values = [];
$('#timesheet').find('input[type="checkbox"]:checked').each(function (index, rowId) {
//this is the current checkbox
var temp = $(this).closest('tr').attr('id');
if (String(temp) === String("undefined")) {
//skip; it is the select all box
}
else {
//push to array
values.push({ Id: temp });
}
});
console.log(values);
$.ajax({
url: "/Admin/ApproveAllTimesheets",
type: "POST",
data: values,
dataType: "html",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (result) {
alert(result);
},
error: function (xhr, textStatus) {
if (xhr.status == 401) { alert("Session Expired!"); window.location = "/Account"; }
else {
alert('Content load failed!', "info");
}
}
});
};
**Method Signature:**
public IActionResult ApproveAllTimesheets( List<Value> values)
**Class**
public class Value
{
public Guid ID { get; set; }
}
UPDATE #3
Model:
public class Value
{
public string TimeId { get; set; }
}
Ajax:
function SubAll() {
//var selectedValues = $('#timesheet').DataTable().column(0).checkboxes.selected().toArray();
var dataJSON = { TimeId: "test" };
console.log(dataJSON);
$.ajax({
url: "/Admin/ApproveAllTimesheets",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(dataJSON),
success: function (result) {
alert(result);
},
error: function (xhr, textStatus) {
if (xhr.status == 401) { alert("Session Expired!"); window.location = "/Account"; }
else {
alert('Content load failed!', "info");
}
}
});
};
Controller:
public ActionResult ApproveAllTimesheets([FromBody]Value information)
You should insert the ids like javascript normal objects :
values.push({
ID: "d88b44e4-1009-47d6-9f2f-f675dca89fe8",
});
Code below is for your reference :
function SubAll() {
var values = [];
values.push({
ID: "d88b44e4-1009-47d6-9f2f-f675dca89fe6",
});
values.push({
ID: "d88b44e4-1009-47d6-9f2f-f675dca89fe7",
});
values.push({
ID: "d88b44e4-1009-47d6-9f2f-f675dca89fe8",
});
$.ajax({
type: "POST",
url: "/Admin/ApproveAllTimesheets",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(values),
success: function (result) {
alert(result);
},
error: function (xhr, textStatus) {
if (xhr.status == 401) { alert("Session Expired!"); window.location = "/Account"; }
else {
alert('Content load failed!', "info");
}
}
});
};
Controller :
public void ApproveAllTimesheets([FromBody]List<Values> value)
{
}
Model :
public class Values
{
public Guid ID { get; set; }
}
If this is your JSON
{ <-- This here is the start of your object
"id": 1;
}
This would need to get bound to a Model
class AnyModel {
public int Id {get; set;}
}
If you have a list in JSON
{
[
...Some objects
]
}
You would need to accept a model of in your controller
class AnyModel {
public List<SomeOtherModel> ListObject {get; set;}
}
Update
You want to store the list of 'Values' in another model.
class Value {
public Guid Id {get;set;}
}
class ValueContainer {
public List<Value> Values {get; set;}
}
Now you want to bind your JSON to your ValueContainer object. When you send JSON you need the [FromBody] for the JSON to get bound to your Model.
public IActionResult ApproveAllTimesheets([FromBody] ValueContainer values) {}
Update 2
Apologies looking through your JS code (old one) a little bit closer you should be using the following structure:
class ValueContainer {
public List<Guid> Id {get; set;}
}
List<Guid> is your values array which you bind to id in your JSON object. Controller stays the same.
public IActionResult ApproveAllTimesheets([FromBody] ValueContainer values) {}
So my Update #3 is working and now I have a different issue so I will post a new question for that.

want to display selected item price in mvc

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.