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;
});
}
},
});
}
Related
I am trying to send the data of my table with dynamic values to the controller.
<tbody>
#if (ViewBag.data != null)
{
foreach (var item in ViewBag.data)
{
<tr>
<td class="AutoId">#item.AutoID <input type="hidden" name="AutoID" value="#item.AutoID" /></td>
<td class="hove" name="text"> <b>#item.Text</b><br /><label></label></td>
<td class="Active">#item.Active</td>
<td id="oBy" name="OrderBy">#item.OrderBy</td>
</tr>
}
}
above is the table structure
I am using below ajax call to send one field for example...
<script>
$(document).ready(function () {
alert("Test 1");
$("#btnSave").click(function (e) {
alert("Test 2");
$.ajax({
type: "POST",
url: '#Url.Action("LookupManagementUpdate", "Admin", new { Area = "Admin" })',
data: $(".hove").val(),
dataType: 'json',
async: false,
success: function (response) {
Success = true;
},
error: function (response) {
},
});
});
});
</script>
Below is my controller code
public string LookupManagementUpdate(string text)
{
return "answer"+Request["text"]+text;
}
I tried using both Request and parameter method to fetch the data but it does not display the table data.
This is a c# mvc ado.net based project
try using Ajax.BeginForm and ajaxOptions Onsuccess
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");
}
});
}
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>
I have a view where i dynamically render checkbox items with razor. User can make adjustments and then i need to send form back to controller. If i send only one item i.e. row, it works fine, but if i try to send all of them i always get null. How can i collect form data properly. This is what i have at the moment.
public void SendData(List<SomeClass> myData)
{
var data = myData; //always null
}
public class SomeClass
{
public int Id { get; set; }
public int RoleId { get; set; }
public bool R { get; set; }
public bool W { get; set; }
public bool E { get; set; }
public bool D { get; set; }
}
And view:
<script type="text/javascript">
$(document).ready(function () {
var test = $("#myForm").serialize();
console.log(test);
test = JSON.stringify({ 'myData': test });
console.log(test);
$.ajax({
contentType: 'application/json; charset=utf-8',
type: 'POST',
url: '/Home/SendData',
data: test,
success: function () {
},
failure: function (response) {
}
});
});
</script>
<form id="myForm">
<div class="row control_group">
#Html.Hidden("Id", 1)
#Html.Hidden("RoleId", 1)
#Html.CheckBox("R", false)
#Html.CheckBox("W", false)
#Html.CheckBox("E", false)
#Html.CheckBox("D", false)
</div>
<div class="row control_group">
#Html.Hidden("Id", 2)
#Html.Hidden("RoleId", 2)
#Html.CheckBox("R", true)
#Html.CheckBox("W", true)
#Html.CheckBox("E", true)
#Html.CheckBox("D", true)
</div>
</form>
EDIT:
This is how i render items with razor
foreach (SomeObject x in items)
{
var menuName = someStringFromDb;
var permissions = x.MainItem.FirstOrDefault();
<div class="row control_group">
<div class="col-sm-4">#menuName</div>
<input name="Id" type="hidden" value="#permissions.Id"/>
<input name="RoleId" type="hidden" value=#permissions.RoleId />
<div class="col-sm-2">
#Html.CheckBox("R", #permissions.Read)
</div>
<div class="col-sm-2">
#Html.CheckBox("W", #permissions.Write)
</div>
<div class="col-sm-2">
#Html.CheckBox("E", #permissions.Edit)
</div>
<div class="col-sm-2">
#Html.CheckBox("D", #permissions.Delete)
</div>
</div>
}
EDIT 2
Thank you for your answer #Avi Fatal it got me this far. Problem i am facing now is this. Checkbox elements rendered by razor have two inputs, one is hidden and other one is shown. When i collect form data i am always getting last input value (hidden one, that's always false) How can i get true value?
Current data sent to controller (everything is false):
{"ajaxData":[{"Id":"1","RoleId":"1","R":"false","W":"false","E":"false","D":"false"},{"Id":"2","RoleId":"2","R":"false","W":"false","E":"false","D":"false"}]}
Collecting data like this (found similar problem here on SO):
var ajaxData = $('.control_group').map(function (i, group) {
var data = {};
$(group).find(':input').each(function () {
data[this.name] = this.value;
});
return data;
}).get();
ajaxData = JSON.stringify({ 'ajaxData': ajaxData });
console.log(ajaxData);
EDIT 3
With only .serialize() i get null as input parameter on controller, with JSON.stringify i get Count = 0, also empty. What am i missing?
HTML:
#model List<WebApplication3.Controllers.HomeController.SomeClass>
<form id="myForm">
#for (int i = 0; i < Model.Count; i++)
{
<div>Element</div>
#Html.HiddenFor(m => m[i].Id)
#Html.HiddenFor(m => m[i].RoleId)
#Html.CheckBoxFor(m => m[i].R)
#Html.CheckBoxFor(m => m[i].W)
#Html.CheckBoxFor(m => m[i].E)
#Html.CheckBoxFor(m => m[i].D)
}
</form>
<button id="send">SEND</button>
<script type="text/javascript">
$('#send').on('click', function () {
var data = $("#myForm").serialize();
console.log(data);
//data = JSON.stringify({ 'ajaxData': data });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/SendData',
data: data,
success: function () {
},
failure: function (response) {
}
});
});
</script>
Controller
public void SendData(IEnumerable<SomeClass> ajaxData)
{
var data = ajaxData;
}
It took me some time to understand the problem (-:
Anyway, I have created a small test, and it is working.
public class User
{
public string UserName { get; set; }
}
public void TestPost(List<User> users)
{
}
you need to serialize your data to json array of objects,
[{ 'UserName': "user 1" }, { 'UserName': "user 2" }] a little jquery manipulation... (see here: Convert form data to JavaScript object with jQuery)
$.ajax({
contentType: 'application/json; charset=utf-8',
type: 'POST',
url: '/Home/TestPost',
data: JSON.stringify([{ 'UserName': "user 1" }, { 'UserName': "user 2" }]),
dataType: "json",
});
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; }
}