model.addAttribute does not work with jquery? - javascript

Ajax sends data to controller. Method uses that data when button is clicked. My method has model.addatribute.Alert post null value. Why?
My Controller
#RequestMapping(value = "index", method = RequestMethod.POST)
#ResponseBody
public List<String> field(#RequestParam("tName") String name,
#RequestParam("dName") String dname, Model model) {
String tn = name;
String dn = dname;
List<String> coname = new ArrayList<>();
try {
Connection mycon2 = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "1996");
DatabaseMetaData metaData2 = mycon2.getMetaData();
ResultSet res4 = metaData2.getColumns(dn, null, tn, "%");
coname = new ArrayList<>();
while (res4.next()) {
String column_name = res4.getString("COLUMN_NAME");
coname.add(column_name);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return coname;
}
Index html
<div id="RightPanel" style="width: 200; height: 100%; float: right;">
<table class="table table-striped">
<input type='text' id='tablehead'/>
<tr>
<th>Column name</th>
</tr>
<tr th:each="name : ${cname}">
<td> th:text="${name}"</td>
</tr>
</table>
</div>
JavaScript in index html
<script th:inline="javascript">
function onclk(a, b) {
var search = {
"tName": a,
"dName": b
};
$.ajax({
type: "POST",
url: "http://localhost:8092/index",
data: search,
dataType: "json",
success: function (data) {
var modelAttributeValue = [[${coname}]];
alert(modelAttributeValue);
},
error: function () {
alert('got error');
}
});
}
</script>

Try this:
<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/
function onclk( a,b) {
var search = {
"tName" : a,
"dName" :b
}
$.ajax({
type: "POST",
url: "http://localhost:8092/index",
data: search,
dataType: "json",
success: function (data) {
var modelAttributeValue = [[${coname}]];
alert(modelAttributeValue); },
error: function(){
alert('got error');
}
});
/*]]>*/
</script>

Related

How to Pass Jsonstringfy object with other parameters

I want pass more parameter with json stringify() but when passing other variable getting null value. please let me know right way of passing more variable .
I have tried this
data: {model:JSON.stringify(arr), buildingid ,shopid,post},
$("#btnArchive").click(function () {
var Buildingid = $("#BuildingId").val();
var shopid = $("#ShopId").val();
var Post = $("#SelectedValue").val();
var arr = [];
debugger;
//Loop through the Table rows and build a JSON array.
var customers = new Array();
$(".tblSavingCollChk:checked").each(function () {
var row = $(this).attr("chkid");
alert(row);
debugger;
//customers.push(row);
arr.push({ Id: row });
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Archive/UpdateStatus",
data: JSON.stringify(arr),
dataType: "json",
success: function (r) {
if (r == true) {
alert("Record Updated successfully");
document.location = '#Url.Action("ArchiveList","Archive")';
}
},
error: function (err) {},
});
});
Controller action
public ActionResult UpdateStatus([FromBody] ArchiveViewModel[] model,string buildingid, string shopid, string Post)//List values)
{}
If you want to pass more variable,I have a work demo like below, you can refer to it:
remove [Frombody] and dataType,contentType
In the controller:
public class jsonPostController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult GetData(Author jsonInput ,string cc, string buildingid, string shopid)
{
return View();
}
}
Index view:
<input type="button" id="btnGet" value="submit" />
<input id="BuildingId" value="aa" type="hidden" />
<input id="ShopId" value="aaa" type="hidden" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(function () {
$("#btnGet").click(function ()
{
// Initialization
var jsonInput = {Id: 23, Name: "John" };
var buildingid = $("#BuildingId").val();
var shopid = $("#ShopId").val();
$.ajax(
{
type: 'POST',
url: '/jsonPost/GetData',
data: {
jsonInput: jsonInput,
cc: "cc", buildingid: buildingid, shopid: shopid
},
});
});
});
</script>
Author:
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
}
result:

Display Information from LINQ query

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;
});
}
},
});
}

How to update the Model value and reload a div in Razor view in MVC

This is my code in Razor view that basically displays the table by extracting information from database -
#model List<EmpoyeeInfo.Models.FFX_HR_Employees>
#using System.Reflection;
#{
ViewBag.Title = "Employee Information";
var Properties = Model[0].GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
string[] head = new string[Properties.Count()];
}
<div id="web-top">
<div id="horizontal-line"></div>
<input class="search-box-text" type="text" spellcheck="false" placeholder="Search Individual Record..." title="Search Individual Record" id="searchbox" name="searchbox" />
</div>
<div id="web-main">
<table class="employee-info">
<tr>
#foreach (var Property in Properties)
{
if (Property.Name.Equals("AnnualHolidayEntitlement"))
{
<th colspan="2">#Property.Name</th>
}
else
{
<th>#Property.Name</th>
}
}
</tr>
#foreach(var Row in Model)
{
<tr>
#{
Type type = Row.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(type.GetProperties());
}
#foreach (PropertyInfo prop in props)
{
if (prop.Name.Equals("AnnualHolidayEntitlement"))
{
<td contenteditable="true">#prop.GetValue(Row, null)</td>
}
else
{
<td>#prop.GetValue(Row, null)</td>
}
}
<td class="saveToDB">SAVE</td>
</tr>
}
</table>
</div>
but as i type in the search box text, an ajax calls are made -
$(document).ready(function () {
$('.search-box-text').keypress(function () {
getReport($(this).html());
});
})
function getReport(Name) {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'POST',
data: { Name: Name },
dataType: "json",
cache: false,
success: function (result) {
//do stuff;
},
error: function () {
console.log("no display");
}
});
}
now how do i reload the div - "web-main" and update the Model value such that as the user searches for a name, the table also needs to be updated.
Code below will append the results to the div 'web-main'. You need to manipulate the success portion of jQuery in your code
$(document).ready(function () {
$('.search-box-text').keypress(function () {
getReport($(this).html());
});
})
function getReport(Name) {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'POST',
data: { Name: Name },
dataType: "json",
cache: false,
success: function (data) {
//do stuff;
console.log(data);
$("web-main").append(JSON.stringify(data));
},
error: function () {
console.log("no display");
}
});
}

How To access and display the data from database using ajax jquery asp.net mvc

I Am trying to fetch the data from database and display it in the page using ajax and jquery. Am new to this platform so can anyone help me
Model:
public class EmployeeModel
{
public int EmpId { get; set; }
public string EmpName { get; set; }
public int Age { get; set; }
public int Salary { get; set; }
}
Controller :
private static readonly string connectionString = ConfigurationManager.ConnectionStrings["ConnStringDb1"].ConnectionString;
public ActionResult GetUser()
{
return View();
}
public JsonResult GetAllUser(int EmpId)
{
List<EmployeeModel> employee = new List<EmployeeModel>();
string query = string.Format("Select * From Employee", EmpId);
SqlConnection connection = new SqlConnection(connectionString);
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
employee.Add(
new EmployeeModel
{
EmpId = int.Parse(reader["EmpId"].ToString()),
EmpName = reader.GetValue(0).ToString(),
Age = int.Parse(reader["Age"].ToString()),
Salary = int.Parse(reader["Salary"].ToString())
}
);
}
}
return Json(employee, JsonRequestBehavior.AllowGet);
}
}
ajax:
#{
ViewBag.Title = "Home Page";
var EmployeeModel = (List<second_day.Models.EmployeeModel>)Model;
}
<div id="id"></div>
<div id="firstName"></div>
<div id="lastName"></div>
<p id="getEmployee">Get Employee</p>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('p#getEmployee').click(function () {
GetEmployeeUsingAjax();
});
});
function GetEmployeeUsingAjax() {
$.ajax({
type: 'GET',
url: '#Url.Action("GetAllUser")',
data:{"EmpId":EmpId},
dataType: 'json',
success: function (data) {
console.log(data);
//$('#id').text(emp.employee.Id);
//$('#firstName').text(emp.employee.FirstName);
//$('#lastName').text(emp.employee.LastName);
},
error: function (emp) {
alert('error');
}
});
}
Here i Need to fetch the data when its success else through error if it doesnt
Am new to this platform can anyone help me
function GetEmployeeUsingAjax() {
var EmpId = 2;
$.ajax({
type: 'GET',
url: '#Url.Action("GetAllUser")',
data: { "EmpId": EmpId },
dataType: 'json',
success: function (data) {
alert(data);
//$('#id').text(emp.employee.Id);
//$('#firstName').text(emp.employee.FirstName);
//$('#lastName').text(emp.employee.LastName);
},
error: function (emp) {
alert('error');
}
});
}
[HttpGet]
public JsonResult GetAllUser(int EmpId)
{
// your code
}
plus string.Format("Select * From Employee where empid = {0} ",EmpId)
Please Check Below code :
var var EmpId = 2;
var abc = {
"EmpId": EmpId
};
$.ajax(
{
url: '/ControllerName/GetAllUser/',
type: "GET",
async: false,
dataType: "json",
contentType: "application/json;",
data: JSON.stringify(abc),
success: function (result) {
alert(data);
}
});
And Action Should Be :
[HttpGet]
public JsonResult GetAllUser(int EmpId)
{
}
Happy !!

Autocomplete - two fields

I'm trying to create a page with fields, that use autocomplete function.
The first field - "ana" works fine. The second fails. I don't see any errors in the console. The prompt doesn't appear.
Here the snippet:
<script src="/inc/jquery-1.8.3.js"></script>
<script src="/inc/jquery-ui.js"></script>
<link href="/inc/jquery-ui.css" rel="stylesheet" type="text/css"/>
<table>
<tr>
<td>Ticker:</td><td><input type="text" name="ana" /></td>
</tr>
<tr>
<td>Cmp: </td><td><input type="text" name="sou" /></td>
</tr>
</table>
<div id="result" style="margin-top:25px;"></div>
<script language="javascript">
$(document).ready(function() {
ana = [ <% getAna %>];
$("input[name='ana']").autocomplete({ source: ana });
sou = [ <% getSou %>];
$("input[name='sou']").autocomplete({ source: sou});
});
</script>
I' cutting getAna and getSou. These works. Here the js/html source code:
<script language="javascript">
$(document).ready(function() {
ana = [ "Aar Edw"];
$("input[name='ana']").autocomplete({ source: ana });
sou = [ "A&A Equity Research"];
$("input[name='sou']").autocomplete({ source: sou});
});
</script>
try this
$(document).ready(function () {
var ana = Array();
$.ajax({
type: "POST",
url: "pagename.aspx/GetAna", //GetAna must be public static web method
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
$.map(data.d, function (item) {
ana.push(item.name);
})
}
});
$("input[name='ana']").autocomplete({ source: ana });
var sou = Array();
$.ajax({
type: "POST",
url: "pagename.aspx/GetSou", //GetSou must be public static web method
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
$.map(data.d, function (item) {
ana.push(item.name);
})
}
});
$("input[name='sou']").autocomplete({ source: sou });
});
in code behind
[WebMethod]
public static List<valuepair> GetAna()//example method same method for GetSou
{
List<valuepair> lstvaluepair = new List<valuepair>();
// ResumeFromBAL objResumeFromBAL = new ResumeFromBAL();
// ResumeFrom objResumeFrom = new ResumeFrom();
DataSet ds = new DataSet();//use your code to get dynamic data
// ds = objResumeFromBAL.GetANA();
if (ds.Tables.Count > 0)
{
foreach (DataRow item in ds.Tables[0].Rows)
{
lstvaluepair.Add(new valuepair() { name = item["ResumeFromName"].ToString(), value = item["ResumeFromId"].ToString() });
}
}
return lstvaluepair;
}
public class valuepair
{
public string name { get; set; }
public string value { get; set; }
}

Categories