Sending data from View to Action - javascript

How do I send some data from the view back to the controller?
This is the select from where I get the data (sel1):
<div class="form-group" style="margin: 0 auto;">
<label for="sel1">Select a cat breed:</label>
<select class="form-control" id="sel1">
#foreach (var item in Model)
{
<option>
#Html.DisplayFor(modelItem => item.BreedName)
</option>
}
</select>
</div>
This is the script I tried to use to send data back:
<script>
$(document).ready(function () {
loadJasonData();
$("#sel1").change(function () {
loadJasonData();
});
});
function loadJasonData() {
$.ajax({
type: "POST",
url: "CatDetails",
//url: "/CatCompare/CatDetails", i also tried this of url
cache: false,
dataType: "json",
data: { name: $("#sel1").val() }
})
}
And finally the controller:
[HttpPost]
[HttpGet]
public ActionResult CatDetails(string name)
{
var breedName = db.Breeds.FirstOrDefault(b => b.BreedName == name);
ViewBag.name = breedName.BreedName;
ViewBag.lifeSpan = breedName.Lifespan;
ViewBag.height = breedName.Height;
ViewBag.weight = breedName.Weight;
ViewBag.shortDescription = breedName.ShortDescription;
return View();
}

First of all you have to add option value to your select:
<div class="form-group" style="margin: 0 auto;">
<label for="sel1">Select a cat breed:</label>
<select class="form-control" id="sel1">
#foreach (var item in Model)
{
<option value='#item.BreedName'>
#Html.DisplayFor(modelItem => item.BreedName)
</option>
}
</select>
</div>
Then change your loadJasonData() method to this
function loadJasonData() {
$.ajax({
type: "POST",
url: "/CatCompare/CatDetails",
cache: false,
dataType: "json",
data: { name: $("#sel1 option:selected").val() }
})
}
at the last remove [HttpGet] in your action
[HttpPost]
public ActionResult CatDetails(string name)
{
var breedName = db.Breeds.FirstOrDefault(b => b.BreedName == name);
ViewBag.name = breedName.BreedName;
ViewBag.lifeSpan = breedName.Lifespan;
ViewBag.height = breedName.Height;
ViewBag.weight = breedName.Weight;
ViewBag.shortDescription = breedName.ShortDescription;
return View();
}
Note: Your action returns a view. If you want to return json result you have to use return Json(yourData);

Related

How to pass model value IFormFile from view to controller On Change event

$(".uploadFile").on('change', function () {
console.log('new file uploaded')
//var array = $("#productImage").getIdArray();
var file_data =$(this).find(".productImage").prop("files")[0];
var files = event.target.files
$(this).find(".imageViewer").attr("src", window.URL.createObjectURL(files[0]));
var form_data = new FormData();
var product_Id = (this.ProductId) ;
var viewModel = { ProductId: product_Id, ProductImage: file_data};
form_data.append("file", file_data);
$.ajax({
url: "/DailyMenuPlanner/AddPhoto",
cache: false,
contentType: false,
processData: false,
data: viewModel,
type: 'post',
success: function (result) {
if (result.success == true) { alert("success!"); }
else { alert("fail!"); }
}
});
});
<div class="col">
<ul class="list-group mt-3">
#if (Model.Products != null && Model.Products.Count > 0)
{
#for (int i = 0; i < Model.Products.Count; i++)
{
<li class="list-group-item">
<input asp-for="#Model.Products[i].IsChecked" type="checkbox" />
<label asp-for="#Model.Products[i].ProductId"> #Model.Products[i].ProductName</label>
<input type="hidden" asp-for="#Model.Products[i].ProductId"/>
<input type="hidden" asp-for="#Model.Products[i].ProductName" asp-route-productId/>
<div class="uploadFile float-end">
<label class="file-label">
<img class="imageViewer" width="50" height="50" style="border: 1px solid #000000; cursor:pointer;" />
</label>
<input asp-for="#Model.Products[i].ProductImage" asp-for-ProductId="#Model.Products[i].ProductId" type="file" class="productImage" onchange="getImage(this.value);" style="visibility:none; display:none"/>
</div>
</li>
}
}
else
{
<li class="list-group-item">nodata</li>
}
</ul>
</div>
[.js]
$(".uploadFile").on('change', function () {
console.log('new file uploaded')
//var array = $("#productImage").getIdArray();
var file_data =$(this).find(".productImage").prop("files")[0];
var files = event.target.files
$(this).find(".imageViewer").attr("src", window.URL.createObjectURL(files[0]));
var form_data = new FormData();
var product_Id = (this.ProductId) ;
var viewModel = { ProductId: product_Id, ProductImage: file_data};
form_data.append("file", file_data);
$.ajax({
url: "/DailyMenuPlanner/AddPhoto",
cache: false,
contentType: false,
processData: false,
data: viewModel,
type: 'post',
success: function (result) {
if (result.success == true) { alert("success!"); }
else { alert("fail!"); }
}
});
});
[controller method]
[HttpPost]
public async Task<JsonResult> AddPhoto(DailySelectedProductViewModel dataModel)
{
IFormFile file = dataModel.ProductImage;
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
byte[] imageAsArray = memoryStream.ToArray();
}
return Json(file.FileName);
}
Here, I am getting null value in my ViewModel from view, I have of one list of elements and each elements have choose file (innput type="file") with them. on choosing any image On Change event get trigger and then it calls the controller method but i am getting stuck that how can i send the model value from view to controller. also the productImage is of datatype = IFormFile. so after getting it pass from view to controller how can i convert it into bytes or does sqlserver column with "image" type save it directly ?
please help me with this issue!
Thank you :)
Try to use data:form-data, and you can insert key with values into this FormData() obj then you can transmit it to your controller. If you want to know more about FormData() then read here
Below is a work demo,you can refer to it:
controller.cs:
public class AAController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> uploader(UploadVm model)
{
return this.View();
}
}
Index.cshtml:
<form id="form" name="form" action="uploader" enctype="multipart/form-data" method="post">
<div class="buttons">
<div class="upload-button">
<input id="id" type="text" />
<input id="type" type="text" />
<input id="files" name="files" type="file" size="1" multiple onchange="uploadFiles('files');" />
</div>
</div>
</form>
#section Scripts{
<script>
function uploadFiles(inputId) {
var input = document.getElementById(inputId);
var files = input.files;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
//Add the input element values
formData.append("Type", $("#type").val());
formData.append("Id", $("#id").val());
$.ajax(
{
url: "/AA/uploader",
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function (data) {
alert("Files Uploaded!");
}
}
);
}
</script>
}
Uploader.cs:
public class UploadVm
{
public string Type { set; get; }
public string Id { set; get; }
public IList<IFormFile> Files { get; set; }
}

In ASP.NET Razor Page Jquery Ajax Function not Working

I have a two onchange function for a page called create delivery request. One is when the dropdownlist of receiver changes, then it should show the phone number & address of receiver selected. Another one is when the dropdownlist of delivery item changes, then it should set the max attribute for the quantity.
The url of both these are linked to the customized OnGet method in razor page.
However, usually the above Onget method is hit but the below one is not. And the above OnGet method can't get the dryfood with the passed ID as well, it is null inside. And the two jQuery ajax function doesn't work at all. I'm totally a beginner. Hope that there is someone who can help me. Thanks in advance.
In create.cshtml:
<div class="mb-3">
Receiver Name
<select id="receiver" asp-for="Delivery.ReceiverID" asp-items="Model.ReceiverList" class="form-control">
<option>--Select the Receiever--</option>
</select>
</div>
<div class="mb-3">
Receiver Phone
<span id="receiverphone" class="form-control">----</span>
</div>
<div class="mb-3">
Receiver Address
<div id="receiveradrs1" class="form-control">----</div>
<div id="receiveradrs2" class="form-control">----</div>
</div>
<div class="mb-3">
Delivery Item
<select id="deliveryitem" asp-for="DeliveryItem.DryFoodID" asp-items="Model.DeliveryItemList" class="form-control">
<option>--Select Delivery Item--</option>
</select>
</div>
<div class="mb-3">
Quantity
<input id="quantity" asp-for="DeliveryItem.Quantity" min="1" class="form-control" />
</div>
In create.csthml.cs, two customized OnGet method here:
public async Task<IActionResult> OnGetSetMaxQuantity(int id)
{
List<DryFoodDonation> dfdlist = await _db.DryFoodDonation.ToListAsync();
var dryfood = dfdlist.Where(d => d.Id == id).FirstOrDefault();
Debug.WriteLine(dryfood.DryFoodName + " " + dryfood.DryFoodRemainQuantity);
return new JsonResult(dryfood.DryFoodRemainQuantity);
}
public async Task<IActionResult> OnGetGetPhoneAdrs(int id)
{
List<User> receiverlist = await _db.User.Where(u => u.UserType.TypeID == 3).ToListAsync();
var selectreceiver = receiverlist.Where(d => d.UserID == id).FirstOrDefault();
Debug.WriteLine(selectreceiver.UserName + " " + selectreceiver.UserPhone);
return new JsonResult(selectreceiver);
}
The jQuery AJAX function in a JavaScript file:
$(document).ready(function () {
$("#receiver").change(function () {
alert('Yes receiver here changed.');
var item = $(this).val();
$.ajax({
type: 'GET',
url: 'Create/?handler=GetPhoneAdrs',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
'id': item
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$('#receiverphone').html(data.UserPhone);
$('#receiveradrs1').html(data.UserAdrs1);
$('#receiveradrs2').html(data.UserAdrs2);
}
});
});
$("#deliveryitem").change(function () {
alert('Yes item here changed.');
var item = $(this).val();
$.ajax({
type: 'GET',
url: 'Create/?handler=SetMaxQuantity',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
"id": item
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$("#quantity").attr({
"min": 1,
"max": data
});
}
});
});
});
Please help me with this. I can't solve this problem for a few weeks. Thank you!
// cshtml.cs
const sendMe = async function (someData) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/ControllerName/MethodNameInController',
data: { someData: someData },
success: function (response) {
if (response != null && response.statusCode == 200) {
..
} else {
..
}
}
});
}
//Controller
[HttpPost("MethodNameInController")]
public IActionResult MethodNameInController([FromForm] string someData) {
..
}

Dynamic DropDownList in ASP.NET MVC NO ACTION RESULT CREATE()

I CANNOT CREATE CASCADING DROPDOWN IN ACTIONRESULT CREATE, ONLY IN ACTION RESULT INDEX IT WORKS
THERE GOES THE CODE
CONTROLLER
public class PessoasController : Controller
{
private GestarkContext db = new GestarkContext();
// GET: Pessoas
public ActionResult Index()
{
ViewBag.Gabinetes = new SelectList(db.Gabinetes, "GabineteId", "Nome");
var pessoageral = db.Pessoas.Include(a => a.gabojecto).Include(a => a.nivelojecto);
return View(pessoageral.ToList());
}
[HttpPost]
public JsonResult getDistricts(int gbtID)
{
List<Departamento> DepartamentoList = db.Departamentoes.Where(p => p.GbtId == gbtID).ToList();
return Json(DepartamentoList, JsonRequestBehavior.AllowGet);
}
VIEW INDEX - IT WORKS HERE
<script>
$(function () {
$('#Gabinetes').change(function () {
var gbtID = $(this).val();
$.ajax({
type: "post",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "getDistricts",
data: "{gbtID:'" + gbtID + "'}",
success: function (data) {
$('#DepartamentoList').empty();
$('#DepartamentoList').append('<option selected="selected" value="">Select Departamento</option>')
$.each(data, function (i, d) {
$('#DepartamentoList').append('<option value=' + d.DircId + '>' + d.Depto + '</option>');
});
},
failure: function (data) {
alert('error occured');
}
});
});
});
</script>
<h2>Lista de Funcioários Registrados</h2>
<br />
<label class="col-md-2 control-label">Gabinete</label>
<div class="col-md-5">
#Html.DropDownList("Gabinetes", null, htmlAttributes: new { #class = "form-control" })
</div>
<div class="form-group">
<label class="col-md-2 control-label">Departamento</label>
<div class="col-md-4">
<select id="DepartamentoList" name="DepartamentoList" class="form-control"></select>
</div>
</div>
<p>
#Html.ActionLink("Visualizar Formulário", "Index", "Principal", null, new { #class = "btn btn-default" }) | #Html.ActionLink("Adicionar Novo", "Create", null, new { #class = "btn btn-primary" }) | #Html.ActionLink("Exportar em Excel", "ExportToExcel", null, new { #class = "btn btn-success" })
</p>
...........
NOW ON VIEW CREATE DOES NOT WORK
I write the code as I do in index, but it doesn't work
I NEED YOUR HELP PLEASE

multiple cascading dropdown with Angular & MVC

Firstly apologies that post looks a bit long winded (it is just repeated code, so looks longer than it is). I'm trying to implement a multiple level cascading dropdown - It works fine for the initial and first level (COLUMN1 & COLUMN2) but not for COLUMN3.
Here is the controller:
public JsonResult GetCol1()
{
using (EntityName db = new EntityName())
{
var ret = db.TABLE_NAME.Select(x => new { x.COLUMN1 }).Distinct().ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
[HttpPost]
public JsonResult GetCol2(string col1)
{
using (EntityName db = new EntityName())
{
var ret = db.TABLE_NAME.Where(x => x.COLUMN1 == col1).Select(x => new { x.COLUMN2 }).Distinct().ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
[HttpPost]
public JsonResult GetCol3(string col1, string col2)
{
using (EntityName db = new EntityName())
{
var ret = db.TABLE_NAME.Where(x => x.COLUMN1 == col1).Where(x => x.COLUMN2 == col2).Select(x => new { x.COLUMN3 }).Distinct().ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
Here is the JS:
app.controller('DropdownPopulation', function ($scope, $http) {
//$http service for Getting Column1
$http({
method: 'GET',
url: '/Data/GetCol1'
})
.success(function (data) {
$scope.Col1Data = data;
});
//$http service for getting Column2
$scope.GetCol2 = function () {
$http({
method: 'POST',
url: '/Data/GetCol2',
data: JSON.stringify({ COLUMN1: $scope.col1 })
}).
success(function (data) {
$scope.Col2Data = data;
});
};
//$http service for getting Column3
$scope.GetCol3 = function () {
$http({
method: 'POST',
url: '/Data/GetCol3',
data: JSON.stringify({ COLUMN1: $scope.col1, COLUMN2: $scope.col2 })
}).
success(function (data) {
$scope.Col3Data = data;
});
};
};
Finally here is the html / angular:
<!-- Column 1 -->
<div ng-controller="DropdownPopulation">
<div class="form-group">
<label class="control-label col-sm-2" for="Column1">Column1</label>
<div class="col-sm-10">
<select class="form-control" name="Column1"
data-ng-model="col1" id="Column1"
data-ng-options="c.COLUMN1 as c.COLUMN1 for c in Col1Data "
data-ng-change="GetCol2()">
<option value="" disabled selected>Select Col 1</option>
</select>
</div>
</div>
<!-- Column 2 -->
<div class="form-group">
<label class="control-label col-sm-2" for="Column2">Column2</label>
<div class="col-sm-10">
<select class="form-control" name="Column2"
data-ng-model="col2" id="Column2"
data-ng-options="c.COLUMN2 as c.COLUMN2 for c in Col2Data "
data-ng-change="GetCol3()"
data-ng-disabled="!Col1Data" >
<option value="" disabled selected>Select Col 2</option>
</select>
</div>
</div>
<!-- Column 3 -->
<div class="form-group">
<label class="control-label col-sm-2" for="Column3">Column3</label>
<div class="col-sm-10">
<select class="form-control" name="Column3"
data-ng-model="col3" id="Column3"
data-ng-options="c.COLUMN3 as c.COLUMN3 for c in Col3Data"
data-ng-disabled="!Col2Data" >
<option value="" disabled selected>Select Col 3</option>
</select>
</div>
</div>
</div>
Col3Data is actually returning empty when there is data in the database.
If you know why Col3Data is not returning back anything then your help would be most appreciated.
Many thanks
Shaheen
Okay i found out what the problem was. When doing the following:
data-ng-options="c.COLUMN1 as c.COLUMN1 for c in Col1Data
I was using 'values' for the first part rather than a 'key', so this was not returning data back.
changing to the following worked:
data-ng-options="c.COLUMN1_KEY as c.COLUMN1 for c in Col1Data
Viplock, thanks for your help as I found:
var dataToSend={ COLUMN1: $scope.col1, COLUMN2: $scope.col2 };
very helpful.
Regards,
Shaheen K
If there will be some issue with digest cycle not worked , you can try using $scope.$apply() like
Update For sending data
$scope.GetCol3 = function () {
var dataToSend={ COLUMN1: $scope.col1, COLUMN2: $scope.col2 };
$http({
method: 'POST',
url: '/Data/GetCol3',
data: dataToSend
}).
success(function (data) {
$scope.Col3Data = data;
$scope.$apply();
});
};

Form is not Submitting any Value using Asp.Net MVC

In Model:
public int TeacherCourseAssignId { set; get; }
public int TeacherID { set; get; }
public decimal TeacherRemainingCredit { set; get; }
public int CourseId { set; get; }
public string CourseName { set; get; }
public decimal CourseCredit { set; get; }
In controller:
[HttpPost]
public ActionResult TeacherCourseAssign(int departmentId, int teacherId, int courseId)
{
ViewBag.Departments = GetDepartments();
return View();
}
public ActionResult SaveTeacherCourseAssign(TeacherCourseAssign teacherCourseAssign)
{
ViewBag.Departments = GetDepartments();
ViewBag.Message = teacherCourseAssignManager.Save(teacherCourseAssign);
ModelState.Clear();
return View();
}
public JsonResult SaveTeacheCourseAssign(TeacherCourseAssign teacherCourseAssign)
{
//Code
return Json(true, JsonRequestBehavior.AllowGet);
}
public JsonResult GetTeachersByDepartmentId(int deptId)
{
var teachers = GetTeacher();
var teacherList = teachers.Where(a => a.DepartmentId == deptId).ToList();
return Json(teacherList, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCoursesByDepartmentId(int deptId)
{
var courses = GetCourses();
var courseList = courses.Where(a => a.DepartmentId == deptId).ToList();
return Json(courseList, JsonRequestBehavior.AllowGet);
}
public JsonResult GetTeachersInfoByTeacherId(int teacherId)
{
var teachers = GetTeacher();
var teacherInfo = teachers.Where(t => t.TeacherID == teacherId).ToList();
return Json(teacherInfo, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCoursesInfoByCourseId(int courseId)
{
var courses = GetCourses();
var courseList = courses.Where(c => c.CourseId == courseId).ToList();
return Json(courseList, JsonRequestBehavior.AllowGet);
}
In View:
#model Last.Models.TeacherCourseAssign
#{
ViewBag.Title = "Teacher Course Assign";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Teacher Course Assign</h2>
<form method="POST" id="myForm">
<table>
<tr>
<td>
<label for="departmentId">Select Department</label>
</td>
<td>
<select name="departmentId" id="departmentId">
<option value="">Select...</option>
#foreach (var department in ViewBag.Departments)
{
<option value="#department.DeptId">#department.DeptName</option>
}
</select>
</td>
</tr>
<tr>
<td><label for="teacherId">Teacher</label></td>
<td>
<select name="teacherId" id="teacherId"></select>
</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.CreditToBeTaken)</td>
<td>#Html.TextBoxFor(m => m.CreditToBeTaken)</td>
</tr>
<tr>
<td>#Html.LabelFor(r => r.TeacherRemainingCredit)</td>
<td>
#Html.TextBoxFor(r => r.TeacherRemainingCredit)
</td>
</tr>
<tr>
<td><label for="courseId"></label></td>
<td>
<select name="courseId" id="courseId"></select>
</td>
</tr>
<tr>
<td>#Html.LabelFor(n => n.CourseName)</td>
<td>
#Html.TextBoxFor(n => n.CourseName)
</td>
</tr>
<tr>
<td>#Html.LabelFor(c => c.CourseCredit)</td>
<td>
#Html.TextBoxFor(c => c.CourseCredit)
<br>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" id="Submit" value="Assign" class="btn btn-default" /></td>
</tr>
</table>
</form>
#section scripts
{
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
$("#departmentId").change(function() {
var dept = $("#departmentId").val();
$("#teacherId").empty();
$("#courseId").empty();
var json = { deptId: dept };
//$("#teacherId").append('<option value="">Select</option>');
$.ajax({
type: "POST",
url: '#Url.Action("GetTeachersByDepartmentId", "TeacherCourseAssign")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function(data) {
$("#teacherId").append('<option value="">Select</option>');
$.each(data, function(key, value) {
$("#teacherId").append('<option value=' + value.TeacherID + '>' + value.TeacherName + '</option>');
});
}
});
// $("#courseId").append('<option value="">Select</option>');
$.ajax({
type: "POST",
url: '#Url.Action("GetCoursesByDepartmentId", "TeacherCourseAssign")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function(data) {
$("#courseId").append('<option value="">Select</option>');
$.each(data, function(key, value) {
$("#courseId").append('<option value=' + value.CourseId + '>' + value.CourseCode + '</option>');
});
}
});
});
$("#teacherId").change(function() {
var tech = $("#teacherId").val();
var json = { teacherId: tech };
$.ajax({
type: "POST",
url: '#Url.Action("GetTeachersInfoByTeacherId", "TeacherCourseAssign")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function(data) {
$.each(data, function(key, value) {
$("#CreditToBeTaken").val(value.CreditToBeTaken);
$("#TeacherRemainingCredit").val(value.CreditToBeTaken);
});
}
});
});
$("#courseId").change(function() {
var tech = $("#courseId").val();
var json = { courseId: tech };
$.ajax({
type: "POST",
url: '#Url.Action("GetCoursesInfoByCourseId", "TeacherCourseAssign")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function(data) {
$.each(data, function(key, value) {
$("#courseName").val(value.CourseName);
$("#CourseCredit").val(value.Credit);
});
}
});
});
});
</script>
}
My Cascading DropDown for department, course and teacher Info is working fine. but when I click on submit. it is not submitting any value to my post controller SaveTeacherCourseAssign(). want to know am i submitting my model in a wrong way?
Are you able to hit the controller at all? By default, all controllers actions listen to GET requests, so if you can't hit it, you would have to decorate it with [HttpPost] in order to hit it.
Also, I don't see any ajax request that's targeting it. Unless it's the form, at which point you might want to explicitly put an action attribute on it if the page/view name is not the same.
If you're in fact hitting a breakpoint when you submit, are you just getting a null object?
Alright, you have your form element but it doesn't have any action property. You have to add it like:
<form method="POST" id="myForm"
action="#Url.Action("your_action_method_name" , "your_controller_name")" >
I think this is what you are missing.

Categories

Resources