Call the same function - c#

I would like whichever button been clicked I want to call the same function.
for now I have six card on View but work only one first. Other dosent work
My view
<h2>Our workouts</h2>
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="col-md-4">
<div class="card" style="width: 18rem;">
<img src="~/Content/not-found-image.jpg" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">#item.Name</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<div id="textButton">
#*Go to anywhere*#
<a id="btnNewSave" class="btn btn-primary">Go to anywhere</a>
<input type="text" id="getValue" value="#item.Id" hidden />
</div>
</div>
</div>
</div>
}
</div>
</div>
My controller:
[HttpGet]
public ActionResult ListCoach(int? Id)
{
var ChoachList = _TraningService.Coach(Id);
return View(ChoachList);
}
script
I call My script from View use helper section
#section scripts {
<script>
$(document).ready(function () {
$("#btnNewSave").click(function () {
var data = $("#getValue").val();
$.ajax({
type: "GET",
url: '/TrainingType/ListCoach',
data: { id: data },
success: function (data) {
console.log(data);
window.location.href = '/TrainingType/ListCoach';
return data;
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
});
});
</script>
}

You should try this way, because your type of buttons are diffrent as per current scenario <a> and button so below way you could try.
Script:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
function PassToContoller(data) {
//alert(data);
$.ajax({
type: "GET",
url: '/UserLog/AnotherListCoach',
data: { id: data },
success: function (data) {
console.log(data);
window.location.href = '/appUser/ManageAccount';
return data;
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
}
$(document).ready(function () {
$("a[name=link]").on("click", function () {
var valueOfClickedTag = $(this).data("index");
alert("Clicked On Anchor: " + valueOfClickedTag);
var callFunc = PassToContoller(valueOfClickedTag)
});
$(":button[id=GoToAnywhere3]").on("click", function () {
var valueOfClickedBtn = $(this).data("index");
var callFunc = PassToContoller(valueOfClickedBtn )
});
});
</script>
}
Razor HTML:
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="col-md-4">
<div class="card" style="width: 18rem;">
#*<img src="~/Content/no_foto.png" class="card-img-top" alt="...">*#
<div class="card-body">
<h5 class="card-title">#item.StudentID</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<div id="textButton">
Go to anywhere
<a class="btn btn-primary" data-index="#item.Name" name="link">Go to anywhere</a>
<input class="btn btn-primary" type="button" id="GoToAnywhere3" data-index="#item.StudentID" value="Save" />
<input type="text" class="inputVal" id="getValue" value="#item.Name" hidden />
</div>
</div>
</div>
</div>
}
</div>
</div>
Output:
Note: <input type="text" class="inputVal" id="getValue" value="#item.StudentID" hidden /> is not needed anymore.
Hope it would completely resolve your problem.

Firstly make use of button type rather than an a. With that change, you can use the onclick event in two ways:
First opt:
<button class="btn btn-primary list-coaches" onclick="listCoaches()">List Coaches</button>
function listCoaches() { ... }
Second opt:
<button class="btn btn-primary list-coaches">List Coaches</button>
$('.list-coaches').click(function() { ... });

Related

Submit Form Data in popup using asp.net core 6.0 Doesn't send AJAX Request to Controller

I want to add new item by send form Ajax to controller and then return json response
this is form to submit putting in partial view "_AddSubAccount"
#model EndSubAccountVM
#using Microsoft.AspNetCore.Mvc.Localization
#inject IViewLocalizer localizer
<form method="post" onsubmit="sendAjax();">
<!-- Modal -->
<div class="modal fade rounded-lg shadow" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content ">
<div class="modal-header bg-info text-white d-flex">
<h5 class="modal-title font-weight-bold" id="exampleModalLabel"><i class="fas fa-plus-circle"></i> #localizer["AddSubAccount"]</h5>
<button type="button" class="close align-self-start mx-1" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body container shadow">
<div class="form-inline mt-3">
<label class="font-weight-bold text-muted align-self-start mx-1 mb-2">#localizer["AccountNameAR"]</label>
<input type="text" asp-for="Name" id="nameAr"
class="form-control w-100 shadow" />
<span class="text-danger" asp-validation-for="Name"></span>
</div>
<div class="form-inline my-3">
<label class="font-weight-bold text-muted align-self-start mx-1 mb-2">#localizer["AccountNameEN"]</label>
<input type="text" asp-for="NameEN" class="form-control w-100 shadow" id="nameEn" />
<span class="text-danger" asp-validation-for="NameEN"></span>
</div>
<input type="hidden" asp-for="AccountTreeId" value="#ViewBag.mainAccountID" id="mainAcc" />
</div>
<div class="modal-footer d-flex justify-content-end">
<button type="button" class="shadow btn btn-secondary mx-1" data-dismiss="modal"><i class="fas fa-cancel"></i> #localizer["Cancel"]</button>
<button type="submit" class="shadow btn btn-primary mx-1"><i class="fas fa-save"></i> #localizer["Save"]</button>
</div>
</div>
</div>
</div>
</form>
and this is View which i inject partial view in call "Add"
#model IEnumerable<EndSubAccount>
#using Microsoft.AspNetCore.Mvc.Localization
#using System.Globalization
#using NToastNotify;
#inject IViewLocalizer localizer
#inject IToastNotification toaster
<h3 class="jumbotron p-3 mb-0 bg-primary-cus text-center text-white font-weight-bold border-cus-3 w-75 container">
<i class="fas fa-list-alt"></i> #localizer["subAccountFor"]
#(CultureInfo.CurrentCulture.Name.StartsWith("ar") ? ViewBag.mainAccountAR : ViewBag.mainAccountEN)
</h3>
<div class="w-75 container p-0 my-2">
<!-- Button trigger modal -->
<button type="button" class="btn btn-sm btn-primary btn-primary-cus addSubAccount" data-toggle="modal" data-target="#exampleModal">
<i class="fas fa-plus-circle"></i> #localizer["addSubAccount"]
</button>
</div>
<table class="table table-sm table-striped table-hover container w-75 rounded-lg">
<thead class="text-white font-weight-bold bg-primary-cus">
<tr>
<th>#localizer["AccountName"]</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
#if (CultureInfo.CurrentCulture.Name.StartsWith("ar"))
{
<td>#item.Name</td>
}
else
{
<td>#item.NameEN</td>
}
<td class="d-flex justify-content-end">
<a asp-rout-id="#item.Id" asp-action="Edit" class="btn btn-sm btn-outline-info mx-1"><i class="fas fa-pencil-alt"></i> #localizer["Edit"]</a>
<a asp-route-id="#item.Id" id="del-btn" class="btn btn-sm btn-danger mx-1"><i class="fas fa-trash-alt"></i> #localizer["Delete"]</a>
</td>
</tr>
}
</tbody>
</table>
<partial name="_AddSubAccount" model="new EndSubAccountVM()" />
<!--! Template To add row in Table -->
<div class="d-none" id="template">
<tr>
#if (CultureInfo.CurrentCulture.Name.StartsWith("ar"))
{
<td>{nameAr}</td>
}
else
{
<td>{nameEn}</td>
}
<td class="d-flex justify-content-end">
<a asp-rout-id="{id}" asp-action="Edit" class="btn btn-sm btn-outline-info mx-1"><i class="fas fa-pencil-alt"></i> #localizer["Edit"]</a>
<a asp-route-id="{id}" id="del-btn" class="btn btn-sm btn-danger mx-1"><i class="fas fa-trash-alt"></i> #localizer["Delete"]</a>
</td>
</tr>
</div>
#section Scripts{
#{ await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
function sendAjax() {
let form = $('form').serialize();
var row2Append = $('table tbody tr:last');
var nameAr = $('#nameAr').val();
var nameEn = $('#nameEn').val();
$.ajax({
url: #Url.Action("Add", "EndSubAccount"),
type: 'post',
data: form,
dataType: 'json',
success: function (response) {
var accountName = CultureInfo.CurrentCulture.Name.StartsWith("ar") ? response.Name : response.NameEN;
var data2Add = $('#template').html().replace('{nameAr}', response.Name)
.replace('{nameEn}', response.NameEN)
.replace('{id}', response.Id);
row2Append.append(data2Add).fadeIn();
toaster.success(localizer["accountSaved", ViewBag.AccountName]);
},
error: function () {
alert({#localizer["someThingError"]});
}
//end of Ajax
});
}
</script>
}
and this is post action to save item and retrun json
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Add(EndSubAccountVM accountVM)
{
var nameArExist = await _context.AccountsTrees.FirstOrDefaultAsync(x => x.Name == accountVM.Name);
var nameEnExist = await _context.AccountsTrees.FirstOrDefaultAsync(x => x.NameEN == accountVM.NameEN);
var AccountIdExist = await _context.AccountsTrees.FirstOrDefaultAsync(x => x.Id == accountVM.AccountTreeId);
// validate Data
if (nameArExist != null)
{
ModelState.AddModelError("Name", _localizer["nameExist"]);
}
if (nameEnExist != null)
{
ModelState.AddModelError("NameEN", _localizer["nameExist"]);
}
if (AccountIdExist == null)
{
ModelState.AddModelError("AccountId", _localizer["AccountIdExist"]);
}
var accountName = CultureInfo.CurrentCulture.Name.StartsWith("ar")? accountVM.Name : accountVM.NameEN;
if (!ModelState.IsValid)
{
_notify.AddErrorToastMessage(_localizer["accountNotSave", accountName]);
return new JsonResult(accountVM);
}
var account2Add = new EndSubAccount()
{
Name = accountVM.Name,
NameEN = accountVM.NameEN,
_lastUpdate = DateTime.Now,
_UserId = Convert.ToInt32(User.FindFirst("UserId").Value),
AccountTreeId = accountVM.AccountTreeId
};
var accountSaved = CultureInfo.CurrentCulture.Name.StartsWith("ar") ? account2Add.Name : account2Add.NameEN;
ViewBag.AccountName = accountName;
await _context.EndSubAccounts.AddAsync(account2Add);
await _context.SaveChangesAsync();
return new JsonResult(accountSaved);
}
when i click on submit it go to action directly without call AJAX so action return response as json in view page not return to AJAX code
so why AJAX Not Work ?
Firstly,try to remove onsubmit="sendAjax();" and change your button to:
<button type="button" class="shadow btn btn-primary mx-1" onclick="sendAjax()"><i class="fas fa-save"></i> #localizer["Save"]</button>
Then the ajax will be called.Since you use [ValidateAntiForgeryToken] in your action,you need to add Antiforgery token to your ajax like this:
function sendAjax() {
let form = $('form').serialize();
var row2Append = $('table tbody tr:last');
var nameAr = $('#nameAr').val();
var nameEn = $('#nameEn').val();
$.ajax({
url: #Url.Action("Add", "EndSubAccount"),
type: 'post',
data: form,
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
dataType: 'json',
success: function (response) {
var accountName = CultureInfo.CurrentCulture.Name.StartsWith("ar") ? response.Name : response.NameEN;
var data2Add = $('#template').html().replace('{nameAr}', response.Name)
.replace('{nameEn}', response.NameEN)
.replace('{id}', response.Id);
row2Append.append(data2Add).fadeIn();
toaster.success(localizer["accountSaved", ViewBag.AccountName]);
},
error: function () {
alert({#localizer["someThingError"]});
}
//end of Ajax
});
----------
}
your form is posting back to server before onsubmit="sendAjax();" fires
so try this :
$("form").submit(function(e){
return false;
});
or :
$('form').on('submit', function(e){
e.preventDefault();
});
further you can remove
onsubmit="sendAjax();"
from form
and change
type="submit"
to
type="button"
for save button
and add
onclick="sendAjax();"
to save button

Passing data to controller in ASP.NET MVC using C#

What am I doing wrong?
I want to pass Id to the controller where I can use it.
My controller
[HttpGet]
public ActionResult ListCoach(int id)
{
List<Training> ListCoachTraining = _TraningService.ListCoach(id);
var ChoachList = _TraningService.Coach(id);
return View(ChoachList);
}
My view - what is correct way call the script? It doesn't work right now:
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="col-md-4">
<div class="card" style="width: 18rem;">
<img src="~/Content/no_foto.png" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">#item.Name</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<div id="textButton">
Go to anywhere
<a id="btnSave" class="btn btn-primary">Go to anywhere</a>
<input class="btn btn-primary" type="button" id="btnSave" value="Save" />
</div>
</div>
</div>
</div>
}
</div>
</div>
//call the script
<script src="#Url.Content("~/scripts/ManagerAccount.js")" type="text/javascript"></script>
My script - I use Ajax for it. There I want to pass id to the controller:
function PassToContoller(data) {
$("#btnSave").click(function () {
$.ajax({
type: "Get",
url: '/TrainingType/ListCoach',
data: { id: data },
success: function (data) {
window.location.href = '/appUser/ManageAccount';
//return data;
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
});
};
You haven't call the function accordingly. You are expecting your PassToContoller function should invoke while you click on save in your case either you have to call this function with btnSave onlick or onClick="PassToContoller(#item.Name)"
I am showing you both here:
When onClick="PassToContoller(#item.Name)" In Line:
Razor HTML
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="col-md-4">
<div class="card" style="width: 18rem;">
#*<img src="~/Content/no_foto.png" class="card-img-top" alt="...">*#
<div class="card-body">
<h5 class="card-title">#item.Name</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<div id="textButton">
Go to anywhere
<a id="btnSave" class="btn btn-primary">Go to anywhere</a>
<input class="btn btn-primary" type="button" id="btnSave" onClick="PassToContoller(#item.Name)" value="Save" />
</div>
</div>
</div>
</div>
}
</div>
</div>
Script:
<script>
function PassToContoller(data) {
alert(data);
$.ajax({
type: "GET",
url: '/ListCoachController/ListCoach',
data: { id: data },
success: function (data) {
console.log(data);
window.location.href = '/appUser/ManageAccount';
return data;
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
}
</script>
Output:
Aother way btnSave Onlick:
In this you need few modifications:
Need to introduce a input type text which will be hidden it will
contrain a value like this <input type="text" id="getValue" value="#item.Name" hidden /> and will pass that hidden value when you
would click the button.
Another thing is your btnSave seems you have used same for other button as well so your onclick function will getConfused which event to fired. So need to set unique btn id Now rest of the same like below:
Razor HTML
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="col-md-4">
<div class="card" style="width: 18rem;">
#*<img src="~/Content/no_foto.png" class="card-img-top" alt="...">*#
<div class="card-body">
<h5 class="card-title">#item.Name</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<div id="textButton">
Go to anywhere
<a id="btnSave" class="btn btn-primary">Go to anywhere</a>
<input class="btn btn-primary" type="button" id="btnNewSave" value="Save" />
<input type="text" id="getValue" value="#item.Name" hidden />
</div>
</div>
</div>
</div>
}
</div>
</div>
Script:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
$("#btnNewSave").click(function () {
var data = $("#getValue").val();
$.ajax({
type: "GET",
url: '/ListCoachController/AnotherListCoach',
data: { id: data },
success: function (data) {
console.log(data);
window.location.href = '/appUser/ManageAccount';
return data;
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
});
});
</script>
}
Update:
Based on your new requirement on comment you just need to update your HTML like below:
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="col-md-4">
<div class="card" style="width: 18rem;">
#*<img src="~/Content/no_foto.png" class="card-img-top" alt="...">*#
<div class="card-body">
<h5 class="card-title">#item.Name</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<div id="textButton">
Go to anywhere
<a class="btn btn-primary" onClick="PassToContoller(#item.Name)">Go to anywhere</a>
<input class="btn btn-primary" type="button" onClick="PassToContoller(#item.Name)" value="Save" />
<input type="text" id="getValue" value="#item.Name" hidden />
</div>
</div>
</div>
</div>
}
</div>
</div>
Note: You have to get rid of id="btnSave" from all the <a> and <button> and need to replace with
onClick="PassToContoller(#item.Name)" it will pass all of your
value. No matter how many cycle you have.
Update with Comment Can I do without?:
HTML:
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="col-md-4">
<div class="card" style="width: 18rem;">
#*<img src="~/Content/no_foto.png" class="card-img-top" alt="...">*#
<div class="card-body">
<h5 class="card-title">#item.Name</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<div id="textButton">
<a href="#" class="btn btn-primary" >Go to anywhere</a>
<a class="btn btn-primary">Go to anywhere</a>
<input class="btn btn-primary" type="button" value="Save" />
<input type="text" id="getValue" value="#item.Name" hidden />
</div>
</div>
</div>
</div>
}
</div>
</div>
Script:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
function PassToContoller(data) {
alert(data);
$.ajax({
type: "GET",
url: '/UserLog/AnotherListCoach',
data: { id: data },
success: function (data) {
console.log(data);
window.location.href = '/appUser/ManageAccount';
return data;
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
}
$(document).ready(function () {
$("a").click(function () {
var data = $("#getValue").val();
var callFunc = PassToContoller(data)
});
$(":button").click(function () {
var data = $("#getValue").val();
var callFunc = PassToContoller(data)
});
});
</script>
}
Hope it would guide you accordingly. You can used either of the approach.
With GET method, you should pass the data via query string
/TrainingType/ListCoach?id=1
In ASP.NET MVC, we have default route template is {Controller}/{Action}/{id}
So, alternative we can use this URL
/TrainingType/ListCoach/1

ASP.NET Core 3.0 Razor JQuery validation rules on partial page

I have a page in ASP.NET Core 3.0 with RAZOR(no MVC), with a partial page loaded with AJAX; load works well but validation rules no. Validation with "required" notation on otherinput fields also works well.
This is my main page:
<a class="nav-link showposition text-dark text-center p-0 collapsed" id="ShowPosition" href='ShowPosition'>#item.Sale_Order_Position</a>
<div class="card shadow mb-4 collapse" aria-labelledby="ShowPosition">
<div id="DetailContents">
</div>
</div>
<script>
jQuery(function($) {
$('.showposition').on('click', function (e) {
e.preventDefault();
$.ajax({
url: $(this).attr('href'),
type: 'GET',
cache: false,
headers: {
RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
}
}).done(function(result) {
$('#DetailContents').html(result);
//Setup Position details
$('#SavePositionForm').SetupPositionDetails();
});
});
(function( $ ){
$.fn.SetupPositionDetails = function () {
$("#SavePositionForm").removeData("validator");
$("#SavePositionForm").removeData("unobtrusiveValidator");
$.validator.unobtrusive.parse("#SavePositionForm");
$("#SavePositionForm").validate({
debug: true,
rules: {
inp_NetPrice: {
required: true
}
}
});
};
})(jQuery);
});
</script>
And this is my Partial View:
<form id="SavePositionForm" class="needs-validation" novalidate>
<div class="col-sm-12 col-md-12 col-lg-6 col-xl-6">
<div class="row">
<div class="col div_image pl-0">
<label class="bg-white"><i class="fr fa-newspaper mr-2"></i><localize>Net price</localize></label>
</div>
<div class="col-sm-6 col-md-6">
<input class="form-control form-control-sm" type="number" step="any" name="inp_NetPrice" id="inp_NetPrice" asp-for="#Model.Item1.Net_Price" value="#Model.Item1.Net_Price"/>
</div>
</div>
</div>
</form>
The problem is "inp_NetPrice" validation not working.
I have also try this script, in main partial page(i know, it's not a good idea to put script in partial pages but I would like to try) without success:
$(document).ready(function () {
$("#SavePositionForm").validate({
debug: true,
rules: {
inp_NetPrice: {
required: true
}
}
});
$("#SavePositionForm").removeData("validator");
$("#SavePositionForm").removeData("unobtrusiveValidator");
$.validator.unobtrusive.parse("#SavePositionForm");
});
Any suggestions?
Thanks.
EDIT:
Generated HTML:
<div class="col-sm-12 col-md-12 col-lg-6 col-xl-6">
<div class="row">
<div class="col div_image pl-0">
<label class="bg-white"><i class="fa fa-newspaper mr-2"></i>Net price</label>
</div>
<div class="col-sm-6 col-md-6">
<input class="form-control form-control-sm" id="inp_NetPrice" name="inp_NetPrice" value="" type="number" step="any">
</div>
</div>
</div>
Problem fixed removing
name="inp_NetPrice"
because i have
name="inp_NetPrice" id="inp_NetPrice" asp-for="#Model.Item1.Net_Price"

Filling other controls by combobox selected item asp.net core Razor Page

I'm new to asp.net core and trying to learn… I've a razor page with some controls. (Asp.Net Core 2.2) and i wanna fill text-boxes or other controls by selecting an item from a combobox… When i used GET method, the data contains html tags… If i use POST no value comes back. Need help to understand if my way is wrong or not
the cshtml as follows
<script type="text/javascript">
$(function () {
$("#txtTcKimlikNo").change(function () {
$.ajax({
url: '#Url.Action("fillOgrenciData")',
type: "POST",
data: { "code": $(this).val() },
"success": function (data) {
if (data != null) {
alert(data);
$("#name").val(data.Okulno);
alert($("#name").val());
alert("ok");
}
}
});
});
});
</script>
<section class="well">
<h2 class="ra-well-title">Öğrenci Bilgileri</h2>
<div class="form-group">
<label class="control-label col-sm-4" for="name">Adı Soyadı</label>
<div class="col-sm-8 col-md-6">
<input id="name" class="k-textbox" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="birthday">Doğum Tarihi</label>
<div class="col-sm-8 col-md-6">
#(Html.Kendo().DatePicker().Name("date").Value("10/09/1979"))
</div>
</div>
</div>
<div class="form-horizontal form-widgets col-sm-6">
<div class="form-group">
<label class="control-label col-sm-4" for="txtTcKimlikNo">Tc Kimlik No</label>
<div class="col-sm-8 col-md-6">
#(Html.Kendo().ComboBox()
.Name("txtTcKimlikNo")
.DataTextField("Tckimlikno")
.DataValueField("Ogrid")
.BindTo(Model.ogrenciler)
.Filter("Contains")
.Height(300)
.Template("<span class=\"k-state-default\">#: data.Adisoyadi #<p>#: data.Okulno #</p></span>"))
</div>
</div>
</div>
and the cshtml.cs is as follows
public void OnGet()
{
Data = _db.Okul.ToList();
EgOgyillar = _db.PrEgogyillar.ToList();
ogrenciler = _db.Ogrenci.ToList();
}
public JsonResult ReadOkul()
{
return new JsonResult(_db.Okul.ToList());
}
[HttpPost]
public ActionResult fillOgrenciData(string code)
{
var query = from c in _db.Ogrenci
where c.Tckimlikno == Convert.ToInt64(code)
select c;
return new JsonResult(query);
}
But i can't fill the name textbox with data.Okulno. It always comes undefined. By the way i didn't use models in app. If it's need to used, i will restart to write the app.

Passing and handling of varibles to a function with AJAX in MVC

I'm having trouble passing a variable into a function in my view. I'm fairly new to MVC and not sure how I save and pass information.
#model Models.Schedule.SheduleModel
#{
Layout = null;
}
<div>
<div class="tableRow">
<p>Make a schedule reminder.</p>
</div>
<div class="tableRow tableRowHeading">
<div class="row" style="width: 210px">Name</div>
<div class="row" style="width: 210px">Number</div>
</div>
#foreach (var shedule in Model.ScheduleList)
{
<div class="tableRow">
#using (Html.BeginForm("UpdateSchedule", "Schedule", FormMethod.Post))
{
<div class="cell" style="width: 210px">
#Html.HiddenFor(model => schedule.Id)
#Html.TextBoxFor(model => schedule.Name, new { #class = "inputFieldText" })
#Html.ValidationMessageFor(model => schedule.Name)
</div>
<div class="cell" style="width: 210px">
#Html.TextBoxFor(model => agent.ContactNumber, new { #class = "inputFieldText" })
#Html.ValidationMessageFor(model => agent.ContactNumber)
</div>
<div class="cell">
<button name="Update" type="submit" value="Update" class="button" title="Update details">
<span class="text">Update</span>
</button>
</div>
<div class="cell">
<button class="button" type="button" onclick="deleteFromSchedule();" value="Delete">
<span class="text">Delete</span>
</button>
</div>
}
</div>
}
</div>
#Scripts.Render("~/bundles/jqueryval")
<script>
function deleteFromSchedule() {
$.ajax(
{
type: 'POST',
url: urlBase + 'Schedule/UpdateSchedule/' + Id,
data:
{
Id: Id
},
success: function (data) {
console.log(data);
},
error: function () {
var errorMessage = 'Error occurred while sending message';
console.log(errorMessage);
}
});
}
}
</script>
I'm trying to pass the schedule Id in HiddenFor into the delete function but everything I try doesn't work, i'm also curious on how to handle the information gotten from the text box in a later unwritten div, I'd like to produce text on the screen saying
User #Model.Name and number #Model.Number will be notified of schedule change but I keep displaying blank spaces. an I use the form I'm creating for this information, what would the syntax be?. My method in the schedule controller is very straight forward.
[HttpPost]
public void UpdateSchedule(int Id)
{
////do stuff here
}
The simplest way is to add your id from the schedule into the inline function call (using razor), and add an id param into your javascript delete function:
<div class="cell">
<button class="button" type="button" onclick="deleteFromSchedule(#schedule.Id);" value="Delete">
<span class="text">Delete</span>
</button>
</div>
<script>
function deleteFromSchedule(id) {
$.ajax(
{
type: 'POST',
url: urlBase + 'Schedule/UpdateSchedule/' + id,
data:
{
Id: id
},
success: function (data) {
console.log(data);
},
error: function () {
var errorMessage = 'Error occurred while sending message';
console.log(errorMessage);
}
});
}
}
</script>

Categories