How to bind jsonresult to label text in mvc using javascript - javascript

I'm trying to bind jsonresult data to label text which are from database but it won't work..
I have posted script code herewith it will get dropdownlist selected value and pass to actionresult and then result data pass as jsonresult
<script>
function getOutletDetails() {
debugger;
var centreName = $("#ddl_Outlet").find("option:selected").text();
$.ajax
({
url: "#Url.Action("OutletDetails", "AddTickets", new {area="Common"})",
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({ centreName: +centreName }),
success: function (result) {
$("#lblTelephone1").text(result.Telephone_01);
},
error: function () {
alert("Whooaaa! Something went wrong..")
},
});
}
</script>
Controller Code
[HttpPost]
public ActionResult OutletDetails(string centreName)
{
List<tbl_Centre> lstcity = new List<tbl_Centre>();
// int id1 = Convert.ToInt32(id);
//ViewBag.Id = id;
lstcity = (objbs.CentreBs.GetAll().Where(x => x.CentreName == centreName)).ToList<tbl_Centre>();
var result = JsonConvert.SerializeObject(lstcity, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
return Json(result, JsonRequestBehavior.AllowGet);
}

Usually .text() will work like this
$('#sampleButton').click(function(){
$('#SampleId').text($('.userInput').val());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id="SampleId">Sample text</label><br><br>
<input class="userInput" style="width: 300px" type="text" value="new value that will be replace at label"><br><br>
<button id="sampleButton">change label text</button>

Related

POST file list to controller in ajax post

I tried to upload documents but I couldnt pass to list my controllers parameter. My scenario is:
user click to "choose file" button and pick the files and press done
then my some functions get file list and pass to controller for save locally via POST merhod like below:
view side: (get file list)
function saveDocuments(documentList) {
if (documentList.length > 0)
{
var formList = new Array;
for (var i = 0; i < documentList.length; i++) {
var form = new FormData();
var file = documentList[i];
form.append('FormFile', file);
formList.push(form);
}
savePhysicalFile(formList);
}
}
view side: (post file list)
function savePhysicalFile(formData)
{
if (formData != null)
{
$.ajax({
url: "Installation/SavePhysicalPath",
type: 'POST',
dataType: "json",
contentType: "multipart/form-data",
data:formData,
processData: false,
contentType: false,
success: function (result) {
console.log("Success", result);
},
error: function (data) {
console.log(data);
}
});
}
}
In my controller side; the parameter "model" is always null. I couldnt pass view side list here. How can I figure out ?
controller side
public JsonResult SavePhysicalPath([FromForm] List<FileModel> model)
{
var savingRootPath = #"C:\MyDocuments";
//I'm doing save locally
return Json(savingRootPath);
}
model side
public class FileModel
{
public string Files { get; set; }
public IFormFile FormFile { get; set; }
}
From your code,you may pay attention to two things here:
1.For each property of the complex type, model binding looks through the sources for the name pattern prefix.property_name. If nothing is found, it looks for just property_name without the prefix.For model you receive in backend is a List,you need give the name like:[index].FormFile or model[index].FormFile.
2.Your model has a IFormFile and your action receives a list model,if you only pass the IFormFile you need remove FromForm attribute and be sure do not have [ApiController].It is a known github issue and this has been moved to Next sprint planning milestone.
Here is a whole working demo:
View:
<input type="file" multiple onchange="saveDocuments(this.files)"/>
<div class="form-group">
<input type="button" value="Submit" id="submit" class="btn btn-primary" />
</div>
#section Scripts
{
<script>
function saveDocuments(documentList) {
if (documentList.length > 0) {
var form = new FormData();
for (var i = 0; i < documentList.length; i++) {
var file = documentList[i];
//change here
form.append('model['+i+'].FormFile', file);
}
savePhysicalFile(form);
}
}
function savePhysicalFile(formData) {
if (formData != null) {
$.ajax({
url: "/Installation/SavePhysicalPath",
type: 'POST',
dataType: "json",
contentType: "multipart/form-data",
data: formData,
processData: false,
contentType: false,
success: function (result) {
console.log("Success", result);
},
error: function (data) {
console.log(data);
}
});
}
}
</script>
}
Controller:
[HttpPost]
public JsonResult SavePhysicalPath(List<FileModel> model)
{
var savingRootPath = #"C:\MyDocuments";
//I'm doing save locally
return Json(savingRootPath);
}
Result:

Jquery ajax post sends null when object fields are set with jquery .val() method

I am using Asp.Net Core MVC. I am trying to post an object to action result using jquery http post. When I set my object with static values, i can see all fields are set properly on client side and backend. Posted object is not null.
When I set fields of request with jquery .val() method. Request object is sent as null to backend. Where am I making mistake ?
$("#saveReport").on("click", function () { //SENDS NULL OBJECT
var request = {
BookId: $("#cmbBook").val(),
PageCount: $("#txtPageCount").val(),
Date: $("#dateReport").val(),
Note: $("#txtNotes").val(),
};
//var request = { //SENDS OBJECT PROPERLY
// BookId: 1,
// PageCount: 10,
// Note: "test"
//};
$.ajax({
type: "POST",
url: appUrl + "Report/AddUserReport",
data: JSON.stringify(request),
success: function (data) {
},
error: function (data) {
},
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
And below is backend
[HttpPost]
public ActionResult<ReadingLogResponse> AddUserReport([FromBody]AddReportModel model)
{
var response = _reportBusiness.AddReport(new AddReadingLogRequest()
{
BookId = model.BookId,
Date = model.Date,
Note = model.Note,
PageCount = model.PageCount
});
return response;
}
jquery .val() method would set the data with string type by default.You need to parse Int.Here is a simple demo like below:
1.Model:
public class AddReportModel
{
public int BookId { get; set; }
public int PageCount { get; set; }
public DateTime Date { get; set; }
public string Note { get; set; }
}
2.View:
<form>
BookID:<input id="cmbBook" type="text" />
PageCount:<input id="txtPageCount" type="text" />
Date:<input id="dateReport" />
Notes:<input id="txtNotes" type="text" />
<input type="button" id="saveReport" value="post" />
</form>
#section Scripts
{
<script>
$("#saveReport").on("click", function () { //SENDS NULL OBJECT
var request = {
BookId: parseInt($("#cmbBook").val()),
PageCount: parseInt($("#txtPageCount").val()),
Date: $("#dateReport").val(),
Note: $("#txtNotes").val(),
};
console.log(request);
console.log(JSON.stringify(request));
$.ajax({
type: "POST",
url: appUrl + "Report/AddUserReport",
data: JSON.stringify(request),
success: function (data) {
},
error: function (data) {
},
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
</script>
}
3.Controller:
[HttpPost]
public ActionResult<ReadingLogResponse> AddUserReport([FromBody]AddReportModel model)
{
//...
}

Delete record by using ajax from database EntityFramework

I am beginner and trying to delete the record from database by using JavaScript, Ajax and Json in MVC Entity Framework. But my delete button is not working well.
In controller class my action code is
public ActionResult Delete(int id) {
using (StudentContext db = new StudentContext()) {
Student std = db.Student.Where(x => x.Id == id).FirstOrDefault<Student>();
db.Student.Remove(std);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
and my JavaScript code is
<button id='deleteRecord'>delete</button>
$("#deleteRecord").click(function () {
var StudentId = $(this).val();
var stdId = parseInt(StudentId);
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
StudentId: stdId
}
}).done(function () {
alert("Deleted")
});
});
}).error(function () {
alert("Failed")
});
I shall be very thankful if anybody help me.
You need to add your model id in jquery data tag:
<button id='deleteRecord' data-model-id="#model.Id">delete</button>
Then in javascript code:
$("#deleteRecord").click(function () {
var StudentId = $(this).data("model-id");
var url = "/AjaxStudent/Delete/" + StudentId;
$.ajax({
url: url,
type: 'Delete',
}).done(function () {
alert("Deleted")
});
});
}).error(function () {
alert("Failed")
});
I think that the error comes from the type attribute of your ajax call. You assign "delete" to this attribute, but it must be "POST":
$.ajax({
url: "#Url.Action("Delete","AjaxStudent")",
type: "POST", // here is your problem,
data: { StudentId: stdId },
dataType: 'json',
success: function() {
alert("Deleted");
},
error: function(dat) {
alert(data.x);
}
});
And the action method in your controller must be decorated with [httppost] :
[HttpPost]
public JsonResult Delete(int StudentId)
{
using (StudentContext db = new StudentContext())
{
Student std = db.Student.Where(x => x.Id == StudentId).FirstOrDefault<Student>();
db.Student.Remove(std);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
you should try by changing :
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
StudentId: stdId
}
to:
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
'id':stdId
}
After lots of time I am able to resolve my problem.
Now my javaScript code
<button class='deleteRecord' data-stid=" + students[i].Id + " >delete</button>
$(".deleteRecord").click(function () {
var StudentId1 = $(this).data("stid");
debugger;
$.ajax({
url: "/AjaxStudent/Delete/" + StudentId1,
type: "Post"
}).done(function () {
getAllStudents();
});
});
});
Controller.cs
public ActionResult Delete(int id) {
using (StudentContext db = new StudentContext()) {
Student std = db.Student.Where(x => x.Id == id).FirstOrDefault();
db.Student.Remove(std);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}

Ajax call to Controller arrives empty in MVC 4

I'm trying to populate one select when the onchange of another select is called. Below is what I have built. My GetLine ActionResult breakpoint is being hit, but the parameter breweryCode is null. The method errors at that point. What am I missing?
Controller:
public ActionResult Index()
{
List<Brewery> breweries = BuildMockBrewery();
ViewBag.Breweries = new SelectList(breweries.AsEnumerable(), "BreweryCode", "BreweryDescription");
return View();
}
public ActionResult GetLine(string breweryCode)
{
List<PackagingLine> packagingLines = BuildMockLine(breweryCode);
SelectList pLine = new SelectList(breweryCode, "LineNumber", "Descriptions", 0);
return Json(pLine);
}
Index.cshtml:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript">
function GetLine(_breweryCode) {
var url = '/Report/GetLine/';
$.ajax({
url: url,
data: { breweryCode: _breweryCode },
cache: false,
type: "POST",
success: function (data) {
alert('called');
var markup = '<option value="0">Select Line</options>';
for (var i = 0; i < data.length; i++) {
markup += '<option value="' + data[i].Value + '">' + data[i].Text + '</options';
}
$('#LineSelect').html(markup).show();
},
error: function (response) {
alert('fail' + ' ' + _breweryCode);
}
});
}
</script>
<div id="report-description">
#using (Html.BeginForm("Index", "Report", FormMethod.Post))
{
#Html.DropDownList("BreweryCode", (SelectList)ViewBag.Breweries, "Select Brewery", new { #class = "ui-select", #ID = "BrewerySelect", #onchange = "javascript:GetLine(this.Value);" })
<select class="ui-select" id="LineSelect" name="ReportSelect">
</select>
}
In your #onchange attribute, change this.Value to this.value
Try add
[HttpPost]
public ActionResult GetLine(string breweryCode)
{
List<PackagingLine> packagingLines = BuildMockLine(breweryCode);
SelectList pLine = new SelectList(breweryCode, "LineNumber", "Descriptions", 0);
return Json(pLine);
}
so GetLine can be able to process POST request
Please add datatype as well:
dataType: 'html', or dataType: 'json'
and add http method in a controller
[HttpPost]
public ActionResult GetLine(string breweryCode)
{
}
Also, make sure whether value _breweryCode is coming in below function
function GetLine(_breweryCode)
{
}
Take below code as sample
$.ajax({
type: "POST",
url: your url,
dataType: 'json',
data: JSON.stringify({ id: '2' }),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('hello');
}
});

Viewmodel contents null after ajax call?

I am creating an ASP.NET MVC application. I am currently developing a search page where both the search box and the table of results are displayed on the same page. To do this I have used Partial Views and AJAX/JSON calls with a viewmodel. After entering the two search terms in the textbox, both are null in the controller after being passed through ajax.
Here is the code:
ViewModel:
public class ExampleViewModel
{
public string search { get; set; }
public string search2 { get; set; }
}
Controller:
[HttpPost]
public ActionResult Search(ExampleViewModel searchTerm)
{
var searchList = db.UserLists.Where(x => x.LastName.Contains(searchTerm.search));
return PartialView("_SearchResultsPartial", searchList);
}
Body of Index View:
<body>
<div>
#Html.TextBoxFor(model => model.search)
#Html.TextBoxFor(model => model.search2)
<input type="submit" value="Search" onclick="return getSearchResults()"/>
</div>
<div id="search-results">
</div>
<script>
var exViewModel = {
search: $('#search').val(),
search2: $('#search2').val()
}
function getSearchResults() {
$.ajax({
type: "POST",
data: JSON.stringify(exViewModel),
dataType: "json",
contentType: "application/json",
url : "/View/Search/",
success: function (result) {
$("#search-results").html(result);
}
});
}
</script>
Again, after setting a breakpoint on the Search [POST] method, the ExampleViewModel's terms are null.
At first sight, it seems that you have to retrieve the values within the function scope:
function getSearchResults() {
//Read these values on button click
var exViewModel = {
search: $('#search').val(),
search2: $('#search2').val()
}
$.ajax({
type: "POST",
data: JSON.stringify(exViewModel),
dataType: "json",
contentType: "application/json",
url : "/View/Search/",
success: function (result) {
$("#search-results").html(result);
}
});
}
Otherwise, the exViewModel is just determined on page load.

Categories

Resources