I have a Partial View as a Table, that will be refreshed with a Dropdown Selection in the Main View. This dropdown list includes company names. In the table below information matters pertaining to each company, and for each line of this information there is a drop-down list of all the functions that I can do with this line (like deleting or modifying the information) with a Pop-up Modal.
How can I call a Method in the main Model or Submit something? Or can I create a Partial View with Model in my Case?
Here is my Main View:
#page
#model Fachinformationsdienst_Kundenportal.Pages.Information_listModel
#{
}
<form>
<div class="form-row align-items-center">
<div class="form-group col-md-4">
<label for="inputState">Wählen Sie eine Unternehmen aus</label>
<select id="inputState" class="form-control">
#for (int i = 0; i < Model.companies.Count; i++)
{
<option>#Model.companies[i].FirmenKurzBezeichnung</option>
}
</select>
</div>
<div class="form-group col-md-6">
<input class="form-control" id="myInput" type="text" style="margin-top: 31px;" placeholder="Suche...">
</div>
<div class="form-group col-md-2">
<button type="button" class="btn btn-primary" style="margin-top: 31px;">
<i class="fas fa-plus"></i>
</button>
</div>
</div>
</form>
<div id="fachinfoContainer">
<partial name="_FachinfoPartial" model="#Model.myViewModel" />
</div>
#section Scripts{
<script type="text/javascript">
$(function () {
$("#inputState").change(function () {
var selectcompany = "";
if ($(this).val() != "Wählen Sie die Firma aus...") {
selectcompany = $(this).val();
}
$.ajax({
url: "/Actions/Information-List?handler=fachinfoPartial",
type: "Get",
data: { company: selectcompany },
success: function (result) {
$("#fachinfoContainer").html(""); //clear the fachinfo container.
$("#fachinfoContainer").html(result); //populate the container.
},
error: function (result) {
alert(result);
}
});
});
});
</script>
}
Here is my Partial View
#model Fachinformationsdienst_Kundenportal.Models.MyViewModel
<table class="table table-striped" id="FachinfoTable">
<thead>
<tr>
<th scope="col">Nr.</th>
<th scope="col">Name</th>
<th scope="col">Status</th>
<th scope="col">Letzte Änderung</th>
<th scope="col">Aktuelle Version</th>
<th scope="col">Auftrag</th>
</tr>
</thead>
<tbody id="myTable">
#if (#Model.Fachinfos != null)
{
#for (int i = 0; i < #Model.Fachinfos.Count; i++)
{
<tr>
<th scope="row">#Model.Fachinfos[i].FachinfoNummer</th>
<td>#Model.Fachinfos[i].FachinfoName</td>
<td>#Model.Fachinfos[i].Status</td>
<td>#Model.Fachinfos[i].Datum</td>
<td>#Model.Fachinfos[i].PdfVersion</td>
<td>
<div class="dropdown">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="caret"></span>
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
#for (int c = 0; c < #Model.SelectedCompany.Permissions.Count; c++)
{
if (Model.SelectedCompany.Permissions[c] != Models.Company.Permission.ERSTERFASSEN && Model.SelectedCompany.Permissions[c] != Models.Company.Permission.ABFRAGEN)
{
<a class="dropdown-item" data-toggle="modal" data-number="#Model.Fachinfos[i].FachinfoNummer" data-version="#Model.Fachinfos[i].PdfVersion" data-target="##Model.SelectedCompany.Permissions[c]">#Model.SelectedCompany.Permissions[c]</a>
}
}
</div>
</div>
</td>
</tr>
}
}
</tbody>
</table>
<!-- The Delete Modal -->
<div class="modal fade" id="#Models.Company.Permission.LOESCHEN">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Bestätigen</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<span id="deletMessege">Sind Sie sicher, dass Sie diese Fachinformation löschen möchten?</span>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button id="confirm" type="submit" class="btn btn-primary">Senden</button>
</div>
</div>
</div>
</div>
<script>
$('##Models.Company.Permission.LOESCHEN').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var fiNumber = button.data('number') // Extract info from data-* attributes
var modal = $(this)
modal.find('.modal-title').text('Fachinfonummer ' + fiNumber)
})
</script>
Here is my main model
using Fachinformationsdienst_Kundenportal.Classes;
using Fachinformationsdienst_Kundenportal.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections.Generic;
namespace Fachinformationsdienst_Kundenportal.Pages
{
public class Information_listModel : PageModel
{
public List<Company> companies { get; set; }
public List<Fachinfo> fachinfos = new List<Fachinfo>();
public MyViewModel myViewModel = new MyViewModel();
public void OnGet()
{
companies = APIRequester.GetCompanies(User.Identity.Name);
foreach (var company in companies)
{
fachinfos.AddRange(APIRequester.GetFachinfos(company.FirmenKurzBezeichnung));
}
}
public PartialViewResult OnGetFachinfoPartial(string company)
{
//based on the selctedcompany to filter data, then return to the partial view.
companies = APIRequester.GetCompanies(User.Identity.Name);
myViewModel = new MyViewModel()
{
SelectedCompany = companies.Find(r => r.FirmenKurzBezeichnung == company), //get the company object here
Fachinfos = APIRequester.GetFachinfos(company)
};
return Partial("_FachinfoPartial", myViewModel);
}
//Submit this Method from Partial view
public IActionResult onDelete(string fiNumber)
{
return Page();
}
}
}
You can use JQUERY AJAX calls for this
$.ajax({
type: "POST",
url: '/Information_listModel?handler=Ondelete',
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
console.log(data.result);
})
your method should return type IActionResult
Related
I am trying to figure out how to get this working.
I am using AngularJS because I do not want to load the complete NPM of Angular and we are using Razor Syntax extensively for the Web Layer
On the Create.cshtml page
<button type="button" ng-click="addApp('Cheese')"
class="btn-sm btn-default no-modal">
Add Applications
</button>
Below is how I have the directory stucture is as follows:
WebLayer
+--wwwroot
+--js
+--applications (Feature)
+applications.component.js
+applications.module.js
+application.template.html
+--delegates (Feature)
+delegates.component.js
+sames as above
+--sponsor-applictions
+same as above
+--lib
+angularjs and all other angularjs files
+app.config.js
+app.module.js
Now I have no problems with getting data below in the sponsor-applictions.component.js I am getting my JSON Object Models arrays from my API.
//Author Moojjoo
//Date 5/3/2019
//sponsor-applications
'use strict';
var testUrl = window.location.hostname;
if (testUrl.includes("localhost")) {
var apiUrl = 'https://localhost:44364';
}
else if (testUrl.includes("uat")) {
var apiUrl = 'https://localhost:44364'; //TODO when the URL is decided for UAT
}
else {
var apiUrl = 'https://localhost:44364'; //TODO when the URL is decided for PRD
}
// Register `sponsorApplications` component, along with its associated controller and template
angular.
module('App').
component('sponsorApplications', {
templateUrl: '../../js/sponsor-applications/sponsor-applications.template.html',
controller: ['$scope', '$http', function SponsorApplications($scope, $http) {
var user_id = $("#User_Id").val();
if (user_id != "") {
$http.get(apiUrl + '/api/v1/Sponsors/' + user_id + '/Applications').then(function successCallback(response) {
$scope.sponsorApplications = response.data;
console.log($scope.sponsorApplications);
}, function errorCallback() {
//var type = 'warning';
//var title = 'User Lookup Required!';
//var body = 'Please enter a User Login ID for lookup'
alert('Please try again later, network error, email sent to application administrator')
});
}
//TODO - Have to get rows from Modal to Page
// Add Rows
$scope.addApp = function (arg) {
debugger;
console.log(arg);
alert(arg);
//$scope.table.push($scope.newApp);
// $scope.newApp = new Object();
};
// Remove Rows
$scope.remove = function (index) {
debugger;
$scope.sponsorApplications.splice(index, 1);
};
}
]
});
I am banging my head against the keyboard trying to figure out why the addApp('Cheese') will not event for for ng-click. $scope.remove function works without any issues.
I really need to understand what I am missing. Thank you and if you need more details simply add a comment.
Edit adding full code
app.config
'use strict';
angular.
module('App').
config(['$routeProvider',
function config($routeProvider) {
$routeProvider.
when('/Sponsors/Create', {
template: '<sponsor-applications></sponsor-applications>'
}).
when('/Sponsors/Create', {
template: '<applications></applications>'
}).
when('/Sponsors/Create', {
template: '<sponsor-delegates></sponsor-delegates>'
}).
when('/Sponsors/Create', {
template: '<delegates></delegates>'
})
}
]);
app.module.js
'use strict';
angular.module('App', [
'ngRoute',
'sponsorApplications',
'applications',
'sponsorDelegates',
'delegates'
])
.run(function () {
console.log('Done loading dependencies and configuring module!');
});
sponsor-applications.component.js
//Author Robert B Dannelly
//Date 4/8/2019
//sponsor-applications
'use strict';
var testUrl = window.location.hostname;
if (testUrl.includes("localhost")) {
var apiUrl = 'https://localhost:44364';
}
else if (testUrl.includes("uat")) {
var apiUrl = 'https://localhost:44364'; //TODO when the URL is decided for UAT
}
else {
var apiUrl = 'https://localhost:44364'; //TODO when the URL is decided for PRD
}
// Register `sponsorApplications` component, along with its associated controller and template
angular.
module('App').
component('sponsorApplications', {
templateUrl: '../../js/sponsor-applications/sponsor-applications.template.html',
controller: ['$scope', '$http', function SponsorApplications($scope, $http) {
var user_id = $("#User_Id").val();
if (user_id != "") {
$http.get(apiUrl + '/api/v1/Sponsors/' + user_id + '/Applications').then(function successCallback(response) {
$scope.sponsorApplications = response.data;
console.log($scope.sponsorApplications);
}, function errorCallback() {
//var type = 'warning';
//var title = 'User Lookup Required!';
//var body = 'Please enter a User Login ID for lookup'
alert('Please try again later, network error, email sent to application administrator')
});
}
//TODO - Have to get rows from Modal to Page
// Add Rows
$scope.addApp = function (arg) {
debugger;
console.log(arg);
alert(arg);
//$scope.table.push($scope.newApp);
// $scope.newApp = new Object();
};
// Remove Rows
$scope.remove = function (index) {
debugger;
$scope.sponsorApplications.splice(index, 1);
};
}
]
});
sponsor-applications.module.js
'use strict';
// Define the `sponsorApplicaitons` module
angular.module('sponsorApplications', []);
sponsor-applications.template.html
<style>
/* Overwrites */
.btn {
width: 100%;
}
</style>
<table class="table-bordered table-striped" style="width:100%;">
<thead style="font-weight:bold">
<tr>
<td>Remove</td>
<td>Application ID</td>
<td>Application Name</td>
</tr>
</thead>
<!-- The naming must be exact application matches the $scope.sponsorApplications
in sponsor-applications.component.js-->
<tr ng-repeat="app in sponsorApplications">
<td>
<a class="btn" ng-click="remove($index)"><i class="fa fa-times" aria-hidden="true"></i></a>
</td>
<td>{{ app.application_ID }}</td>
<td>{{ app.application_Name }}</td>
</tr>
</table>
Create.cshtml -- ASP.NET Core w/ Razor Syntax ----
#model WEB.ViewModels.AddSponsorViewModel
#using WEB.HtmlHelpers
#{
ViewData["Title"] = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!-- Alert Display will be used as a standard on all page simply add this to your page
https://www.trycatchfail.com/2018/01/22/easily-add-bootstrap-alerts-to-your-viewresults-with-asp-net-core/
https://www.trycatchfail.com/2018/02/21/easy-bootstrap-alerts-for-your-api-results-with-asp-net-core/-->
#await Html.PartialAsync("~/Views/Shared/_StatusMessages.cshtml")
<h2>Sponsor Information</h2>
<form asp-action="Create" id="CreateSponsor">
#Html.AntiForgeryToken()
#*<input type=hidden asp-for="User_ID" />*#
<input type="hidden" id="User_Id" name="User_Id" value="" />
<div class="form-horizontal">
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="col-md-12">
<row>
<div class="form-group col-md-5">
<label asp-for="Domain_ID" class="control-label"></label>
<br />
<input asp-for="Domain_ID" class="form-control" />
<span asp-validation-for="Domain_ID" class="text-danger"></span>
</div>
<div class="col-md-2">
</div>
<div class="form-group col-md-5">
<label asp-for="Name" class="control-label"></label>
<br />
<input asp-for="Name" class="form-control" />
#*#Html.AutocompleteFor(model => Core.Models.SearcherUser.Name, model => Core.Models.SearcherUser.Email, "GetSponsor", "Approval", false)*#
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</row>
</div>
<div class="col-md-12">
<row>
<div class="form-group col-md-12">
<label asp-for="Email" class="control-label"></label>
<br />
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</row>
</div>
<div class="col-md-12" style="margin-top:20px">
<row>
<div class="col-md-6">
<strong>Delegates</strong> <asp:button formnovalidate="formnovalidate" id="addDelegate" style="cursor: pointer" class="btn-xs btn-primary" data-toggle="modal" data-target="#delegatesModal">Add</asp:button>
<!-- AngularJS defined in wwwroot > js > sponsor-applications -->
<sponsor-delegates></sponsor-delegates>
</div>
<div id="divMyAppCtrl" class="col-md-6">
<strong>Applications</strong> <asp:button formnovalidate="formnovalidate" id="addApplication" style="cursor: pointer" class="btn-xs btn-primary" data-toggle="modal" data-target="#appModal">Add</asp:button>
<!-- AngularJS defined in wwwroot > js > sponsor-applications -->
<br />
<sponsor-applications></sponsor-applications>
</div>
</row>
</div>
<div class="col-md-12" style="margin-top:50px;">
<row>
<div class="col-md-2">
<input type="submit" value="Delete" disabled class="btn btn-default" />
</div>
<div class="col-md-offset-6 col-md-2" style="text-align:right">
<input type="submit" value="Save" class="btn btn-default" />
</div>
<div class="col-md-2">
<button class="btn btn-default" type="button" id="cancel" onclick="location.href='#Url.Action("Index", "Sponsors")'">Cancel</button>
</div>
</row>
</div>
</div>
</form>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
<!-- Modal to select delegates for sponsor -->
<div class="modal fade" tabindex="-1" role="dialog" id="delegatesModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<strong>Please select the Delegates</strong>
<div id="delgates_tbl">
<!-- AngularJS defined in wwwroot > js > applications -->
<delegates></delegates>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn-sm btn-default no-modal" data-dismiss="modal" id="closeDelegate">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Add Applications Button in Modal
<!-- Modal to select application for sponsor -->
<div class="modal fade" tabindex="-1" role="dialog" id="appModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<strong>Please select the applications</strong>
<div id="divModalApps">
<!-- AngularJS defined in wwwroot > js > applications -->
<applications></applications>
</div>
</div>
<div class="modal-footer">
<button type="button"
ng-click="addApp('Cheese')"
class="btn-sm btn-default no-modal">
Add Applications
</button>
<button type="button" class="btn-sm btn-default no-modal"
data-dismiss="modal" id="closeApps">
Close
</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
----
the button HTML is on the Create.cshtml page, but so are all the templates aka
<sponsor-applications>
</sponsor-applications>
Also note that in the _Layouts.cshtml page all js files are referenced. ~/app.module.js, ~/app.config.js, ~/js/sponsor-delegates/sponsor-delegate.module.js, ~/js/sponsor-delegates/sponsor-delegates.component.js
sponsor-applications.component.js
//Author Robert B Dannelly
//Date 4/8/2019
//sponsor-applications
'use strict';
var testUrl = window.location.hostname;
if (testUrl.includes("localhost")) {
var apiUrl = 'https://localhost:44364';
}
else if (testUrl.includes("uat")) {
var apiUrl = 'https://localhost:44364'; //TODO when the URL is decided for UAT
}
else {
var apiUrl = 'https://localhost:44364'; //TODO when the URL is decided for PRD
}
// Register `sponsorApplications` component, along with its associated controller and template
angular.
module('App').
component('sponsorApplications', {
templateUrl: '../../js/sponsor-applications/sponsor-applications.template.html',
controller: ['$scope', '$http', function SponsorApplications($scope, $http) {
var user_id = $("#User_Id").val();
if (user_id != "") {
$http.get(apiUrl + '/api/v1/Sponsors/' + user_id + '/Applications').then(function successCallback(response) {
$scope.sponsorApplications = response.data;
console.log($scope.sponsorApplications);
}, function errorCallback() {
//var type = 'warning';
//var title = 'User Lookup Required!';
//var body = 'Please enter a User Login ID for lookup'
alert('Please try again later, network error, email sent to application administrator')
});
}
//TODO - Have to get rows from Modal to Page
// Add Rows
**********************BELOW is the correct SYNTAX********************
this.addApp = function (arg) {
alert(arg);
debugger;
console.log(arg);
};
//$scope.addApp = function (arg) {
// debugger;
// console.log(arg);
// alert(arg);
// //$scope.table.push($scope.newApp);
// // $scope.newApp = new Object();
//};
// Remove Rows
$scope.remove = function (index) {
debugger;
$scope.sponsorApplications.splice(index, 1);
};
}
]
});
Create.cshtml Changes
In the template
<div id="divMyAppCtrl" class="col-md-6">
<strong>Applications</strong> <asp:button formnovalidate="formnovalidate" id="addApplication" style="cursor: pointer" class="btn-xs btn-primary" data-toggle="modal" data-target="#appModal">Add</asp:button>
<!-- AngularJS defined in wwwroot > js > sponsor-applications -->
<br />
<sponsor-applications ng-ref="sponsorApplications"></sponsor-applications>
</div>
Add Applications Modal in the footer
<div class="modal-footer">
<button type="button" ng-click="sponsorApplications.addApp('CLicked')" class="btn-sm btn-default no-modal">Add Applications</button>
<button type="button" class="btn-sm btn-default no-modal" data-dismiss="modal" id="closeApps">Close</button>
</div>
im trying to post to mvc.core controller textarea value & id value & im getting js error "result is not defined "
and the only data the controller getting the id value .
Razor:
<div class="well">
<div class="row">
<form asp-action="AddToSellList" method="post" class="form-horizontal shadow" style="padding: 10px;">
#foreach (var item in Model)
{
<div class="well well-sm" style="background-color: white;">
<div class=" row">
<div class="col-sm-10 pull-right text-right">
#* Prop *#
#foreach (var qestion in item.QAViewModel)
{
<div id="#item.Id" class="collapse" style="background-color: gray">
<p>Qestion</p>
#* Prop *#
#foreach (var ansewr in qestion.Answers)
{
#* Prop *#
}
</div>
}
</div>
<div class="col-sm-2">
<button class="btnShowModal btn btn-primary btnWhiteSpace" id="#item.Id" type="button" value="#item.Id">
#item.Id
<i class="fas fa-info-circle" aria-hidden="true"></i>
</button>
<button type="button" class="btn btn-info" data-toggle="collapse" data-target="##item.Id"> <i class="fas fa-question-circle" aria-hidden="true"></i>Bla bla </button>
</div>
</div>
</div>
//Check box for selecting items for Action AddToSellList
<input type="checkbox" name="Hiden" value="#item.Id"/>
}
<button type="submit" id="btt"> submit to Action AddToSellList</button>
</form>
</div>
</div>
<div class="modal fade" tabindex="-1" id="loginModal"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-sm ">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<i class="fas fa-window-close"></i>
</button>
<h4 class="modal-title">moder for posting for _AskQ </h4>
</div>
<div class="modal-body ">
<form asp-action="_AskQ" class="form-horizontal" style="padding: 10px; " method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" name="id" asp-for="#Model.First().SiteUserId" />
<div class="form-group">
<textarea name="Question" type="text" class="abc form-control text-right"id="a" required=""> </textarea>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4">Ask</button>
</div>
</form>
</div>
</div>
</div>
</div>
Js:`
<script type="text/javascript">
$(document).ready(function() {
$('.collapse').on('shown.bs.collapse',
function() {
$(".collapse").addClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down');
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$(".btnShowModal").click(function() {
$("#loginModal").modal('show');
var id = $(this).attr("id");
//$(".button4").click(function(e) {
// e.preventDefault();
$(".button4").click(function() {
url = '#Url.Action("_AskQ", "Bid")';
const value = $.trim($("textarea").val());
if (value === "") {
alert(value);
}
var data = {
Id: id,
value: value
};
console.log(id);
console.log(value);
$.ajax({
url: url,
data: data,
type: "POST"
}).done(function(result) {
$(id).html(result);
}).fail(function(x, s, e) {
alert("failed: " + s);
});
});
}
);
});
`
controller :
[HttpPost]
public IActionResult _AskQ(QAViewModel Vm)
{
if (!ModelState.IsValid)
{
return View(Vm);
}
var qustion = new QuoteQuestion
{
SiteUserId = _userManager.GetUserId(User),
QuoteId = Vm.Id,
Question = Vm.Question
};
_context.quoteQuestions.Add(qustion);
_context.SaveChanges();
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
ViewBag.q = qustion.Question;
ViewBag.Id = qustion.QuoteId;
ViewBag.SiteUId = qustion.SiteUserId;
}
return RedirectToAction("Index");
}
public class QAViewModel
{
public int QuoteQuestionId { get; set; }
public int Id { get; set; }
public string Question { get; set; }
public string SiteUserId { get; set; }
public virtual IList<Answers> Answers { get; set; }
}
In the data after ajax call, I can see the Id value & the Value value, but it keep failing to actually post to the controller (Id value only).
I'm posting from ActionResult name :index to ActionResult name _AskQ
Try the following changes in your code ,pay attention to the passed data name should be consistent with the parameter in the action
$(".button4").click(function() {
const value = $.trim($("textarea").val());
if (value === "") {
alert(value);
}
var Vm = {
Id: id,
Question: value
};
console.log(id);
console.log(value);
$.ajax({
type: "POST",
url: "/Bid/_AskQ",
contentType: "application/json",
data: "json",
data: JSON.stringify(Vm),
success: function (result) {
$(id).html(result);
},
error: function (x, s, e) {
alert("failed: " + s);
}
});
});
Add the [FromBody] attribute on the parameter when passing the json type data
[HttpPost]
public IActionResult _AskQ([FromBody]QAViewModel Vm)
Then the return value of the _AskQ method should be the html json result that you want to render the place with the specify id .Make the modification according to your needs。
<script type="text/javascript">
document.getElementById("subcategory").addEventListener("change", function() {
console.log(this.value);
});
$(function(){
$('.categoryList').click(function(){
console.log($(this).attr("name"));
var cat_id = event.target.value;
var url = "http://localhost:8000/api/getSubcategory/"+cat_id;
$.ajax({
type: "GET",
url: url,
dataType: "JSON",
success: function(res)
{
var html = "";
$.each(res, function (key, value) {
html += "<li class="+'subcategorys'+" value="+key+" name="+value+">"+value+" </li>";
});
$('#subcategory').html($(html).addClass('subcategoryList'));
$('.subcategorys').on('click', function(event) {
console.log($(this).attr("name"));
var subcat_id =event.target.value;
console.log(subcat_id);
});
}
});
});
});
$(document).ready(function() {
$('#subcategory').on('click', function(event) {
var subcat_id =event.target.value;
console.log(subcat_id);
var url = "/api/getSubcategorytwo/"+subcat_id;
$.ajax({
type: "GET",
url: url,
dataType: "JSON",
success: function(res)
{
var html = "";
$.each(res, function (key, value) {
html += "<li value="+key+">"+value+"</option></li>";
});
$("#subcategorytwo").html(html);
}
});
});
$('#subcategorytwo').on('click', function(event) {
var opt_subcat_two =event.target.value;
var opt = $(event.target).text();
console.log(opt,opt_subcat_two);
$( "#fetchvalue" ).replaceWith("<input type='text' class='form-control' name='subcategorytwo' value="+opt_subcat_two+" id='fetchvalue' data-toggle='modal' data-target='#myModal'> "+opt+"</input>");
$('#myModal').modal('hide');
$('.modal-backdrop').remove();
});
});
</script>
<input type="text" class="form-control" name="subcategorytwo" id="fetchvalue" data-toggle="modal" data-target="#myModal" ></input>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog modal-lg" >
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<a type="button" class="close" data-dismiss="modal" aria-hidden="true">×</a>
</div>
<div class="modal-body">
<div class="row">
<table class="table table-striped">
<thead>
</thead>
<tbody class="table">
<tr>
<td style="background-color: green">
<div class="col-md-7" >
#foreach($categories as $category)
<option class="categoryList" name="{{$category->category}}" value="{{$category->id}}">{{$category->category}}</option>
#endforeach
</div>
</td>
<td>
<div class="col-md-7">
<ul style="list-style: none" id="subcategory"></ul>
</div>
</td>
<td>
<div class="col-md-7">
<ul style="list-style: none" name="subcategorytwo" id="subcategorytwo" ></ul>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
Here is javascript code and modal code...I have total 4 table...
category subcategory
subcategory
subcategorytwo
post table
all are connected to a foreign key
Post table structure
When try to save category value, subcategory value, subcategorytwo value error is
How can I store 3 value at a time different place in db
Modal show like this
Modal like this
MySQL is most likely in STRICT mode try to
change the column to allow null:
ALTER TABLE `posts` CHANGE `subcategory2` `subcategory2` varchar NULL
Or try running
SET GLOBAL sql_mode='' or
In the view (Index.cshtml) I have a button, when I click on that, the script that in the selectedItems writes the data is triggered. how are selectedItems transferred to the controller?
Button:
<form method="post" asp-action="Delete">
<button type="submit" onclick="SelectedCheckbox()" class="btn-group col-md-2 col-md-offset-0">Remove</button>
</form>
JS:
function SelectedCheckbox() {
var selectedItems = new Array();
$("input[id='check']:checked").each(function () { selectedItems.push($(this).val()); });
}
Controller (Users):
[HttpPost]
public async Task<ActionResult> Delete(string[] selectedUsers)
{
...
return RedirectToAction("Index");
}
I tried to use ajax, but something does not work out:
function SelectedCheckbox()
{
$.ajax({
url: "/Users",
contentType: "application/json",
method: "POST",
data: { parameters: parameters },
success: function (data) {
var data = new Array();
$("input[id='check']:checked").each(function () { data.push($(this).val()); });
alert(data.result);
},
error: function (data) { alert(data.responseText); }
})
}
#model IEnumerable<Task1.Models.User>
#{
ViewBag.Title = "Список пользователей";
}
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<div class="btn-toolbar nl container col-md-12" role="toolbar" aria-label="Menu">
<form method="post" asp-action="Delete">
<button type="submit" onclick="SelectedCheckbox()" name="delete" id="delete" class="btn-group col-md-2 col-md-offset-0">Remove</button>
</form>
<form method="post" asp-controller="Account" asp-action="LogOff">
<button type="submit" class="col-md-2 col-md-offset-3 " role="group" aria-label="LogOff" />LogOff</button>
</form>
</div>
<form asp-action="Delete">
<div class="nl">
<table class="table table-striped table-bordered ">
<tbody class="table-responsive ">
<tr><th><input type="checkbox" class="all" data-id="d1" title="Выбрать все"></th><th>Login</th><th>Date of registration</th><th>Date Last Login</th><th>Block disabled</th></tr>
#foreach (var user in Model)
{
<tr>
<td>
<input type="checkbox" name="selectedUsers"
id="#user.Id" value="#user.Id"
class="styled">
</td>
<td>#user.UserName</td>
<td>#user.DateOfRegistration</td>
<td>#user.DateLastLogin</td>
<td>#user.LockoutEnabled</td>
</tr>
}
</tbody>
</table>
</div>
</form>
<script type="text/javascript">
function SelectedCheckbox() {
var selectedItems = new Array();
$("input[id='check']:checked").each(function () { selectedItems.push($(this).val()); });
alert(selectedItems);
return (selectedItems);
}
</script>
I need to pass the value of the selected Item from the script in the method of removing the controller
Hello i am using MVC 5 c# with ado net code , i am inserting master data and master detail data when i insert data and click save all then event fire but value not pass to controller obj show null value , i try a lot but i could not find problem that's why i am sharing code and help senior people maybe you could understand better and easy find problem. i am sharing javascript code view code and controller code function code . when i debug javascript code i did not find any problem in javascript and there is no error in javascript code .
View
<main class="pt-5 mx-lg-5">
<div class="container-fluid mt-5">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_content">
<div class="panel panel-primary">
<div class="panel-heading">
</div>
<div class="panel-body" style="background-color:#F0FFFF">
<button type="button" id="btnAddnew" class="btn btn-primary" data-toggle="modal" data-target="#centralModalLGInfoDemo" style="float:right">Add New</button>
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Sr No</th>
<th>Item Desc</th>
<th>Qty</th>
<th>Remarks</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Requisitions)
{
<tr>
<td>#Html.DisplayFor(module => item.Srno)</td>
<td>#Html.DisplayFor(module => item.ItemDesc)</td>
<td>#Html.DisplayFor(modelItem => item.Qty)</td>
<td>#Html.DisplayFor(modelItem => item.Remarks)</td>
<td>
<a onclick="GetDetails(#item.ReqNo)">
<i class="fa fa-edit"></i>
</a>
<a>
#Html.ActionLink(" ", "DeleteCustomer", "Home", new { id = item.ReqNo }, new { onclick = "return confirm('Are sure wants to delete?');", #class = "fa fa-trash-o" })
</a>
</td>
</tr>
}
</tbody>
<tfoot>
</tfoot>
</table>
</div>
</div>
</div>
<!---End-->
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="centralModalLGInfoDemo" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-notify modal-info" role="document">
<!--Content-->
<div class="modal-content" style="width:140%">
<!--Header-->
<div class="modal-header">
<p class="heading lead">Add New Requisition</p>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" class="white-text">×</span>
</button>
</div>
<!--Body-->
<form id="NewOrderForm">
<div class="modal-body">
<div class="form-row">
<div class="col">
<!-- Requisition Date -->
<div class="md-form">
#Html.TextBox("ReqNo", (String)ViewBag.ReqNo, new { #class = "form-control mr-sm-3", #id = "txtRequisitionno" })
<label for="lblRequisition">Requisition No.</label>
</div>
</div>
<div class="col">
<!-- Requisition Date -->
<div class="md-form">
#Html.TextBoxFor(m => m.ReqDate, new { #class = "form-control", #id = "txtRequisitionDatepicker" })
<label for="lblRequisitionDatepicker">Requisition Date</label>
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
#Html.TextBoxFor(m => m.Job, new { #class = "form-control", #id = "txtjob" })
<label for="lbljob">Job</label>
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
#Html.TextBoxFor(m => m.Approvedby, new { #class = "form-control", #id = "txtApprovedby" })
<label for="lblApprovedby">Approved by</label>
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
<div class="custom-control custom-checkbox">
<span style="float:right">
#Html.CheckBoxFor(m => m.IsApproved, new { #class = "custom-control-input", #id = "defaultChecked2" })
<label class="custom-control-label" for="defaultChecked2">Approved</label>
</span>
</div>
</div>
</div>
</div>
<!--Detail-->
<h5 style="margin-top:10px;color:#ff6347">Requisition Details</h5>
<hr />
<div>
<div class="form-row">
<div class="col-md-1">
<!-- Requisition Date -->
<div class="md-form">
<input type="text" id="SrNo" name="SrNo" placeholder="Srno" class="form-control" />
<label for="lblSrno">Sr No.</label>
</div>
</div>
<div class="col-md-4">
<!-- Requisition Date -->
<div class="md-form">
#Html.DropDownListFor(m => m.ItemCode, ViewBag.Items as List<SelectListItem>, new { #class = "form-control", id = "txtItemcode" })
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
<input type="number" id="Qty" name="Qty" placeholder="Qty" class="form-control" />
<label for="lbljob">Qty</label>
</div>
</div>
<div class="col">
<!-- Job -->
<div class="md-form">
<input type="text" id="Reemarks" name="Reemarks" placeholder="Remarks" class="form-control" />
<label for="lblRemarks">Remarks</label>
</div>
</div>
<div class="col-md-2 col-lg-offset-4">
<a id="addToList" class="btn btn-primary">Add To List</a>
</div>
</div>
<table id="detailsTable" class="table">
<thead style="background-color:#33b5e5; color:white">
<tr>
<th style="width:2%">SrNo.</th>
<th style="width:40%">Items</th>
<th style="width:15%">Qty</th>
<th style="width:30%">Remarks</th>
<th style="width:10%"></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="saveRequisition" type="submit" class="btn btn-danger">Save Order</button>
</div>
</div>
</form>
</div>
<!--/.Content-->
</div>
</div>
</div>
</main>
javascript
<script>
//Show model
function addNewOrder()
{
$("#NewOrderForm").modal();
}
// Add Multiple Record
$("#addToList").click(function (e) {
e.preventDefault();
if ($.trim($("#SrNo").val()) == "" || $.trim($("#txtItemcode").val()) == "" || $.trim($("#Qty").val()) == "" || $.trim($("#Reemarks").val()) == "") return;
var Srno = $("#SrNo").val(),
items = $("#txtItemcode").val(),
qty = $("#Qty").val(),
remark = $("#Reemarks").val(),
detailsTableBody = $("#detailsTable tbody");
var ReqItems = '<tr><td>' + Srno + '</td><td>' + items + '</td><td>' + qty + '</td><td>' + remark + '</td><td> <a data-itemId="0" href="#" class="deleteItem">Remove</a></td></tr>';
detailsTableBody.append(ReqItems);
clearItem();
//After Add A New Order In The List
function clearItem()
{
$("#SrNo").val('');
$("#txtItemcode").val('');
$("#Qty").val('');
$("#Reemarks").val('');
}
// After Add A New Order In The List, If You Want, You Can Remove
$(document).on('click', 'a.deleteItem', function (e)
{
e.preventDefault();
var $self = $(this);
if ($(this).attr('data-itemId') == "0") {
$(this).parents('tr').css("background-color", "white").fadeOut(800, function () {
$(this).remove();
});
}
});
//After Click Save Button Pass All Data View To Controller For Save Database
function saveRequisition(data) {
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: "/Home/RequisitionInsert", // function save
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!")
}
});
}
//Collect Multiple Order List For Pass To Controller
$("#saveRequisition").click(function (e)
{
e.preventDefault();
var requisitionArr = [];
requisitionArr.length = 0;
$.each($("#detailsTable tbody tr"), function () {
requisitionArr.push({
Srno: $(this).find('td:eq(0)').html(),
items: $(this).find('td:eq(1)').html(),
qty: $(this).find('td:eq(2)').html(),
remark: $(this).find('td:eq(3)').html(),
});
});
var data = JSON.stringify({
txtRequisitionno: $("#txtRequisitionno").val(),
txtRequisitionDatepicker: $("#txtRequisitionDatepicker").val(),
txtjob: $("#txtjob").val(),
txtApprovedby: $("#txtApprovedby").val(),
defaultChecked2: $("#defaultChecked2").val(),
item: requisitionArr
});
$.when(saveRequisition(data)).then(function (response) {
console.log(response);
}).fail(function (err) {
console.log(err);
});
});
});
</script>
Controller
[HttpPost]
public ActionResult RequisitionInsert(Requisition objModel, List<Requisition> oblist)
{
try
{
int result = objclsRequisition.RequisitionInsert(objModel, oblist);
if(result==1)
{
ViewBag.Message = "Your record has been inserted Successfully";
ModelState.Clear();
}
else
{
ViewBag.Message = "Unsucessfull";
ModelState.Clear();
}
return RedirectToAction("Requisition", "Home");
}
catch (Exception)
{
throw;
}
}
Function
public int RequisitionInsert(Requisition Req, List<Requisition> objlist)
{
try
{
con.Open();
tr = con.BeginTransaction();
cmd = new SqlCommand("Sp_RequisitionMainInsert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ReqNo", Req.ReqNo);
cmd.Parameters.AddWithValue("#Comp_ID", "1");
cmd.Parameters.AddWithValue("#GL_Year", "2018-2019");
cmd.Parameters.AddWithValue("#ReqDate", Req.ReqDate.ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("#Job", Req.Job);
cmd.Parameters.AddWithValue("#ApprovedBy", Req.Approvedby);
cmd.Parameters.AddWithValue("#UserName", System.Web.HttpContext.Current.Session["AgentName"]);
cmd.Parameters.AddWithValue("#IsApproved", Req.IsApproved);
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
for (int i = 0; i < objlist.Count; i++)
{
cmd = new SqlCommand("Sp_RequisitionDetailInsert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ReqNo", Req.ReqNo);
cmd.Parameters.AddWithValue("#Comp_ID", "1");
cmd.Parameters.AddWithValue("#GL_Year", "2018-2019");
cmd.Parameters.AddWithValue("#SrNo", Req.Srno);
cmd.Parameters.AddWithValue("#ItemCode", Req.ItemCode);
cmd.Parameters.AddWithValue("#Qty", Convert.ToDecimal(Req.Qty));
cmd.Parameters.AddWithValue("#Remarks", Req.Remarks);
}
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
tr.Commit();
return i;
}
catch (SqlException sqlex)
{
tr.Rollback();
throw sqlex; // read all sql error
}
catch (Exception ex)
{
tr.Rollback();
throw ex; // General execption
}
finally
{
con.Close();
}
}
The issue lays in the api model definition.
You have declared your methods parameters as this
[HttpPost]
public ActionResult RequisitionInsert(Requisition objModel, List<Requisition> oblist)
But, when posting data in MVC you can only have one input model as that model will be parsed straight from the complete request body.
To solve this, create a request model where you define the properties to read from the body.
public class RequestModel
{
public string TxtRequisitionno { get; set; }
public string TxtRequisitionDatepicker { get; set; }
public string Txtjob { get; set; }
public string TxtApprovedby { get; set; }
public string DefaultChecked2 { get; set; }
public List<Requisition> Items { get; set; }
}
And then use it
[HttpPost]
public ActionResult RequisitionInsert(RequestModel model)
NOTE: I have declared the properties in the RequestModel as the same you try to send from the client
Your client model:
{
txtRequisitionno: $("#txtRequisitionno").val(),
txtRequisitionDatepicker: $("#txtRequisitionDatepicker").val(),
txtjob: $("#txtjob").val(),
txtApprovedby: $("#txtApprovedby").val(),
defaultChecked2: $("#defaultChecked2").val(),
item: requisitionArr
};