I am building a small application using ASP.NET MVC Core 3.1.
I am displaying few buttons on the View. Each row has a button. When a button is clicked corresponding to a row, I want to get the ID value of this row but without page refresh. It should be done using AJAX.
The View code is something like this:
#using Updater.Models
#model IEnumerable<TemplateData>
#{
Layout = null;
}
#{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
#if (Model.Count() > 0)
{
<hr />
<table cellpadding="0" cellspacing="0" border="1" style="height:600px">
<tr>
<th>ID</th>
<th>Location</th>
<th>Observation Type</th>
<th>EmpName</th>
<th>Status</th>
</tr>
#foreach (TemplateData sheet in Model)
{
<tr>
<td>#sheet.ID</td>
<td>#sheet.Location</td>
<td>#sheet.ObservationType</td>
<td>#sheet.EmpName</td>
<td>
#Html.DropDownList("CI Status", new List<SelectListItem>
{
new SelectListItem{ Text="", Value = "0" },
new SelectListItem{ Text="Completed", Value = "1" },
new SelectListItem{ Text="In-Progress", Value = "2" },
new SelectListItem{ Text="Review", Value = "3" },
})
</td>
</tr>
<tr>
<td>
#using (Html.BeginForm("Index", "sheet", FormMethod.Post))
{
<input type="submit" value="Update Status" class="ids" data-id="#sheet.ID" />
}
</td>
</tr>
}
</table>
}
</div>
<script type="text/javascript">
$('.ids').click(function() {
var rowID = $(this).data('id');
alert(rowID);
});
</script>
** Edited **
In continuation of what Costa suggested below to call controller from Javascript, I attempted below code, but instead of showing message, it is directing to URL: http://localhost/sheet
<tr>
<td>
#using (Html.BeginForm("Index", "sheet", FormMethod.Post))
{
<input type="submit" id="btnSubmit" value="Update Status" class="ids" data-id="#sheet.ID" onClick="UpdateStatus(#sheet.ID)"/>
}
</td>
</tr>
}
</table>
}
</div>
<script type="text/javascript">
$.ajax({
type: "POST",
url: '#Url.Action("Home", "UpdateStatus")',
contentType: "application/json; charset=utf-8",
data: id,
dataType: "json",
success: function() { alert('Success'); },
error: function() { alert('Error'); }
});
</script>
Controller Code
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
[HttpPost]
[Route("UpdateStatus")]
public void UpdateStatus()
{
//Do Something
}
}
If you want to pass the ID to javascript, you can use this:
<input type="submit" value="Update Status" class="ids" data-id="#sheet.ID" onClick="UpdateStatus(#sheet.ID)" />
<script>
function UpdateStatus(string id) {
$.ajax({
type: "POST",
url: "/UpdateStatus",
contentType: "application/json; charset=utf-8",
data: {"id": id},
dataType: "json",
success: function() { alert('Success'); },
error: function() { alert('Error'); }
});
}
</script>
Finally, edit your controller like this:
[HttpPost]
[Route("UpdateStatus/{id}")]
public void UpdateStatus(string id)
{
//Do Something
}
Related
So I have a string that has been passed from JS to my controller like so:
JavaScript
function findEmployees(userCounty) {
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("getCounty", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
});
}
Controller
[HttpPost]
public ActionResult Index([FromBody] string userCounty)
{
var county = userCounty.Substring(0, userCounty.IndexOf(" "));
var query = from m in _context.model where m.county == county select new Model
{
FirstName = m.Firstname
LastName = m.LastName
};
if (query == null)
{
return NotFound();
}
return View(query.ToList());
}
[HttpGet]
public ActionResult Index()
{
return View();
}
View
#model Project.Models.ModelName
<table class="table">
<tbody>
<tr>
<td>
#Html.DisplayFor(model => model.FirstName) #Html.DisplayFor(model => model.LastName)
</td>
</tr>
</tbody>
I am able to pass the string from JS to my controller and query the database but how do I update the page to show the results of the query in my view? Anything helps. Thank you!
The data returned by ajax is text or json. If you want to use c# to update the page. You can make action getCounty return partial view, partial view automatically returns data with html.
Change action getCounty.
[HttpPost("getCounty")]
public ActionResult Index([FromBody] string userCounty)
{
var county = userCounty.Substring(0, userCounty.IndexOf(" "));
//...
return PartialView(query.ToList());
}
PartialView Index.cshtml
#model List<ModelName>
<table class="table">
<tbody>
#for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(model => model[i].FirstName) #Html.DisplayFor(model => model[i].LastName)
</td>
</tr>
}
</tbody>
</table>
View
#model ModelName
<div id="datalist">
</div>
<!--other code-->
#section Scripts{
<script>
function findEmployees(userCounty) {
$.ajax({
type: "POST",
//dataType: "json",
url: '#Url.Action("getCounty", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
success: function (data) {
$('#datalist').html(data)
},
error: function (e) {
console.log(e)
}
});
}
</script>
}
It can generate different data tables according to userCounty
You can get the list to the page like this.You can then press inside a div or ul list with each loop.
function findEmployees(userCounty) {
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("getCounty", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
success: function (result) {
if (result.data.length !== 0) {
$.each(result.data, function (index, value) {
var firstName = value.firstName;
var lastName = value.lastName;
});
}
},
});
}
Hi i want to post just a simple string to a controller action in asp.net mvc5.
Im trying to do this for hours and cant find a solution on how it works.
I have tried many different solutions without one of them working in how I want.
For hours...
I have a simple view:
#{
ViewBag.Title = "Rollen und Rechte";
}
<form>
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
<div id="mydiv"></div>
</form>
#section scripts {
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}
</script>
}
The thing is that the function is never called.
What is wrong here?
And... in the next step I want to update div id mydiv
How can I change that without return a complete view in the controller and force a reload?
Thanks in advance :)
You are missing a closing parenthesis right before your closing </script> tag:
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}**)**
</script>
instead of using button click event use the following
$(document).on("submit", "form", function (event) {
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
alert(data);
},
error: function (xhr, desc, err) {
}
})
}
you can use ajax.BeginForm of mvc
like this :
#using (Ajax.BeginForm("YourActionName", "YourControllerName", new AjaxOptions {
InsertionMode = InsertionMode.Replace, //target element(#mydiv) will be replaced
UpdateTargetId = "mydiv"
}))
{
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
}
<div id="mydiv"></div>
and in yourController :
public PartialViewResult YourActionName(string name)
{
return PartialView("_YourPartialView");
}
_YourPartialView is a partial View that you want to return replace it with "mydiv" And how to make it with VIEW is the same
if your partial view has a model you should do this :
return PartialView("_YourPartialView",yourModel);
I wanna pass down model from partialView to javascript and process it in controller,
now the problem is i couldn't pass the model where when i run the code it show null. can anyone help me on this?
*HTML code
#model List<TPMS.Models.Draft_SingleValue>
<div class="row">
<div class="col-lg-12">
<table class="table table-bordered">
<thead>
<tr class="bg-gray">
<th>Keyword</th>
<th>Default Value <span class="pull-right"><i class="fa fa-edit"></i></span></th>
<th><span class="pull-right"><i></i></span></th>
</tr>
</thead>
<tbody>
#foreach (var sdata in Model.OrderBy(i => i.Keyword))
{
<tr id="#sdata.DraftSingleValue_ID">
<td id="sv:#sdata.DraftSingleValue_ID:Keyword" contenteditable="false">#sdata.Keyword</td>
<td id="sv:#sdata.DraftSingleValue_ID:Default_Value" contenteditable="false"> #sdata.Default_Value</td>
<td id="sv:#sdata.DraftSingleValue_ID" contenteditable="false" class="">
<span class="btn-group center-block" id="PlusButton">
<a class="btn btn-success btn-xs" href="javascript:AddKeyword('#sdata');" data-id="#sdata"><i class="fa fa-plus"></i> </a>
</span>
</td>
</tr>
}
</tbody>
<tfoot>
<tr class="bg-gray">
<th>Keyword</th>
<th>Default_Value <span class="pull-right"><i class="fa fa-edit"></i></span></th>
<th><span class="pull-right"><i></i></span></th>
</tr>
</tfoot>
</table>
</div>
</div>
*Javascript
function AddKeyword(SvModel) {
debugger
//var model = $('#Testing').attr('data-id');
$.ajax({
url: "#Url.Action("AddSingleValue", "Draft")",
cache: false,
type: "GET",
datatype: 'html',
data: {"Model": SvModel },
success: function (data) {
$('#List_Keyword').modal('hide');
$("#List_SVKeywords").html(data);
$('#List_Keyword').modal('show');
},
error: function () {
alert('Failed to retrieve values.');
document.getElementById("del_err_span_dialog").innerHTML = "Fatal Error, Please try again.";
}
});
}
*Controller
public ActionResult AddSingleValue(Draft_SingleValue Model)
{
Draft_SingleValue svmodel = new Draft_SingleValue();
svmodel.Draft_File_ID = Model.Draft_File_ID;
svmodel.Data_Type = Model.Data_Type;
svmodel.Group_Name = Model.Group_Name;
svmodel.Is_Active = Model.Is_Active;
svmodel.Keyword = Model.Keyword;
svmodel.Max_Length = Model.Max_Length;
svmodel.Min_Length = Model.Min_Length;
svmodel.Modified_By = User.Identity.Name;
svmodel.Modified_On = DateTime.Now;
svmodel.Remarks = Model.Remarks;
svmodel.Default_Value = Model.Default_Value;
_temporaryrepo.Insert_TemporarySingleValue(svmodel);
return ListSv(svmodel.Draft_File_ID);
//return new EmptyResult();
}
As you guys can c from above code, im trying to pass model to AddKeyword function but i cant. it will be great if anyone can show me a way to do this.
Try this:
View:
#using (Html.BeginForm("YourActionMethod", "YourController", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
//code omitted for brevity
}
<script>
$(function () {
$('form').submit(function (event) {
event.preventDefault();
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("YourActionMethod", "YourController")',
data: formdata, //! your model data
dataType: "json",
success: function (response) {
if (response.success) {
//success
}
else {
//error
}
}
});
});
});
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult YourActionMethod([Bind(Exclude = null)] Model viewModel)
{
//...
return Json(new { success = true, message = "Success!.." },
JsonRequestBehavior.AllowGet);
}
I have a jquery datatable UI that I want to bind with my data returned using an ajax call.
The view on which I want to display uses a partial view.
On my controller the I return a json type.
I can get the data from the ajax call but IE downloads it, intead of binding the data with the jquery datatable UI.
I tried to add the jquery script on both the main view and the partial view but none is working.
Here is my code on my controller:
[HttpPost]
public ActionResult Index(LShViewModel model, string Command)
{
if (Command == "Search")
{
//model.CountryIdSelected = model.CountryID;
//model.CountryIdSelected = null;
var results = helper.SearchUsers(model.UserName, model.EmailAddress, model.FirstName, model.LastName, model.CountryID);
if (model.SearchRecords == null)
{
model.SearchRecords = new List<SearchUserResult>();
}
foreach (var result in results)
{
model.SearchRecords.Add(result);
}
//model.SearchRecords = results;
}
model.States = new SelectList(helper.ListStates(model.CountryID), "ID", "Name");
model.Countries = new SelectList(helper.ListCountries(), "ID", "Name");
model.CountryIdSelected = model.CountryID;
// jsonResult.maxJsonLength = int.MaxValue;
return Json(model);
}
here is the scrip on my index page:
<script>
$('#search').click(function () {
$('#searchResults').dataTable({
"ajax": {
"url": "/Learner/Index",
"dataSrc": "",
"dataType": "json",
"success": function (data) {
$('#searchResults').dataTable({
data: data,
columns: [
{ 'data': 'UserName' },
{ 'data': 'Email' },
{ 'data': 'FirstName' },
{ 'data': 'MiddleName' },
{ 'data': 'LastName' },
{ 'data': 'Address' },
{ 'data': 'City' },
{ 'data': 'StateID' },
{ 'data': 'PostalCode' },
{ 'data': 'Phone' },
{ 'data': '' },
]
})
}
}
});
var table = $('#searchResults').dataTable();
table.fnClearTable();
table.fnDraw();
$.ajax({
url: '/Learner/Index',
method: 'post',
dataType: 'json',
dataSrc: "",
success: function (data) {
$('#searchResults1').dataTable({
data: data,
columns: [
{ 'data': 'UserName' },
{ 'data': 'Email' },
{ 'data': 'FirstName' },
{ 'data': 'MiddleName' },
{ 'data': 'LastName' },
{ 'data': 'Address' },
{ 'data': 'City' },
{ 'data': 'StateID' },
{ 'data': 'PostalCode' },
{ 'data': 'Phone' },
{ 'data': '' },
]
});
}
});
})
</script>
here is my partial view:
<div class="col-md-12">
<h4>Search Results</h4>
</div>
<div class="col-md-12">
<table id="searchResults" class="display" cellspacing="0" width="100%">
<thead>
<tr>
#*<th> Select</th>*#
<th>Username</th>
<th>Email</th>
<th>First Name</th>
<th>MI</th>
<th>Last Name</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
<th>Phone</th>
<th></th>
#*<th>CE Type</th>*#
</tr>
</thead>
<tbody>
#{
for (var i=0; i < Model.SearchRecords.Count; i++)
{
<tr>
<td>
#*#Html.CheckBox("Select")*#
#Model.SearchRecords[i].UserName
#Html.HiddenFor(modelItem => Model.SearchRecords[i].CountryID)
#Html.HiddenFor(modelItem => Model.SearchRecords[i].CountryCode)
#Html.HiddenFor(modelItem => Model.SearchRecords[i].PersonID)
#Html.HiddenFor(modelItem => Model.SearchRecords[i].Email)
#Html.HiddenFor(modelItem => Model.SearchRecords[i].FirstName)
#Html.HiddenFor(modelItem => Model.SearchRecords[i].MiddleName)
#Html.HiddenFor(modelItem => Model.SearchRecords[i].LastName)
#Html.HiddenFor(modelItem => Model.SearchRecords[i].Address)
#Html.HiddenFor(modelItem => Model.SearchRecords[i].City)
#Html.HiddenFor(modelItem => Model.SearchRecords[i].UserName)
#Html.HiddenFor(modelItem => Model.SearchRecords[i].PostalCode)
#Html.HiddenFor(modelItem => Model.SearchRecords[i].Phone)
#*#Html.HiddenFor(modelItem => Model.SearchRecords[i].ACPEID)
#Html.HiddenFor(modelItem => Model.SearchRecords[i].AAVSBID)*#
#*#Html.HiddenFor(modelItem => Model.SearchRecords[i].CH)*#
#*#Html.HiddenFor(modelItem => Model.SearchRecords[i].PhysicianTypeID)*#
</td>
<td>#Model.SearchRecords[i].Email</td>
<td>#Model.SearchRecords[i].FirstName</td>
<td>#Model.SearchRecords[i].MiddleName</td>
<td>#Model.SearchRecords[i].LastName</td>
<td>#Model.SearchRecords[i].Address</td>
<td>#Model.SearchRecords[i].City</td>
<td>#Model.SearchRecords[i].StateCode</td>
<td>#Model.SearchRecords[i].PostalCode</td>
#if (Model.SearchRecords[i].Phone != "INVALID")
{
<td>#Model.SearchRecords[i].Phone</td>
}
#if (Model.SearchRecords[i].Phone == "INVALID")
{
<td> <text></text></td>
}
<td>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
Manage
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li role="presentation"><a role="menuitem" tabindex="-1" href="#Url.Action("ViewProfile1", "Learner", new { personid=Model.SearchRecords[i].PersonID})">View Profile</a></li>
</ul>
</div>
</td>
</tr>
}
}
</tbody>
</table>
</div>
I have created a partial view which will open when clicking a button in home page. I have Added datatable in partial view. Please check the following code.
Index.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<script src="http://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet">
<script type="text/javascript">
$(function () {
$('#showDatatable').click(function () {
$("#partialViewDiv").html('');
var request = $.ajax({
url: "Learner/GetPartialView",
method: "POST",
dataType: "html"
});
request.done(function (msg) {
$("#partialViewDiv").html(msg);
$("#partialViewDiv").dialog({
height: 400,
resizable: false,
width: 800,
title: "Search"
});
createDatatableGrid();
});
});
function createDatatableGrid() {
$('#searchResults').dataTable({
bFilter: false,
bLengthChange: false,
"sDom": 'lfrtip',
pagingType: 'full',
"oLanguage": {
"oPaginate": {
"sFirst": "<b><<</b>",
"sLast": "<b>>></b>",
"sNext": "<b>></b>",
"sPrevious": "<b><</b>"
}
}
});
}
createDatatableGrid();
});
</script>
</head>
<body>
<button id="showDatatable" type="button">Show Datatable</button>
<div id="partialViewDiv"></div>
</body>
</html>
LearnerController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class LearnerController : Controller
{
//
// GET: /Learner/
public ActionResult GetPartialView()
{
return PartialView("Partial1");
}
public JsonResult Index()
{
List<User> user = new List<User>();
user.Add(new User()
{
Username = "User1",
Email ="user1#u.com",
FirstName = "FirstName1",
MI = "MI1",
LastName = "LastName1",
Address = "Address1",
City = "City1",
State = "State1",
Zip = "Zip1",
Phone = "Phone1",
});
return Json(user, JsonRequestBehavior.AllowGet);
}
}
}
Partial1.cshtml
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "Learner/Index",
dataType: "json",
success: function (values) {
$('#searchResults').dataTable().fnClearTable();
for (var i = 0; i < values.length; i++) {
var user = values[0];
$('#searchResults').dataTable().fnAddData([
user.Username,
user.Email,
user.FirstName,
user.MI,
user.LastName,
user.Address,
user.City,
user.State,
user.Zip,
user.Phone,
""
]);
}
},
error: function (err) {
console.log(err);
}
});
});
</script>
<div class="col-md-12">
<h4>Search Results</h4>
</div>
<div class="col-md-12">
<table id="searchResults" class="display" cellspacing="0" width="100%">
<thead>
<tr>
#*<th> Select</th>*#
<th>Username</th>
<th>Email</th>
<th>First Name</th>
<th>MI</th>
<th>Last Name</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
<th>Phone</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
**User Model**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication1.Models
{
public class User
{
public string Username { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string MI { get; set; }
public string LastName { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
}
}
I have created this example in MVC4 application.
I am new to mvc and javascript.At first I am using javascript to appned the parital view in divsion
$('.btngo').click(function (e) {
var fid = $('#FiscalYear_FYId').val();
alert($('#FiscalYear_FYId').val());
$.ajax({
type: 'Get',
url: '#Url.Action("RateList", "Rate")',
data: { fyid: fid },
success: function (sc) {
$('#Ratelist').html(sc);
}
});
});
The partial view is of model FHIControl.Model.StationeryRate.RateDTO which consists a submit button my view looks like
#using (Html.BeginForm("Ratelist", "Rate", FormMethod.Post))
{
#Html.ValidationSummary(true)
<table>
<thead>
<tr>
<th>Item Id</th>
<th>Item Name</th>
<th>Rate</th>
</tr>
</thead>
#Html.HiddenFor(x=>Model.FiscalYear.FYId)
#foreach (var item in Model.RateList)
{
<tr>
#Html.HiddenFor(x => item.ItemId)
<td>#{count++;}#count</td>
<td>#Html.DisplayFor(x => item.ItemName)</td>
<td>#Html.TextBoxFor(x => item.Rate)</td>
</tr>
}
</table>
<p>
<input type="submit" value="Ok" id="btnsubmit" />
</p>
}
The button submit is submiting the form but there is no model items.Why is it so?Is there any way to make this work?
There is no model items because you are only passing the value of FiscalYear_FYId:
var fid = $('#FiscalYear_FYId').val();
$.ajax({
data: { fyid: fid },
});
which should be:
$.ajax({
data: $form.serialize(),
});
where $form is a reference to your form. That you can either give a name for faster and better reference, or you can reference it like this:
var $form = $("#btnsubmit").parents('form');