Thanks to #NikhilGhuse, which solution have been sent to me (please mark his answer). I can apply this solution to my data these are the results and the keys:
First of all my model need to send a List to the controller. This is my my function to send the List:
public List<VistaModelo> SegundaConsulta()
{
//Web.Config
Entities db = new Entities();
var consulta = from varLocal in db.LecturaContadorLuzAANDRES
group varLocal by varLocal.dispositivo into subconsulta
select subconsulta.OrderByDescending(t => t.unixtime).FirstOrDefault();
List<LecturaContadorLuzAANDRES> lista = consulta.ToList();
List<VistaModelo> listaVistaModelo = new List<VistaModelo>();
foreach (LecturaContadorLuzAANDRES b in lista)
{
VistaModelo objLista = b.pasaObjetoAVistaModelo();
listaVistaModelo.Add(objLista);
}
return listaVistaModelo;
}
Then in my controller I need two functions:
Consulta 6. Read the list and transform to JSON (you need: using Newtonsoft.Json; in the controller:
public JsonResult Consulta6()
{
var Consulta = new ConsultaContraBD();
List<VistaModelo> miSegundaConsulta = Consulta.SegundaConsulta();
return Json(miSegundaConsulta, JsonRequestBehavior.AllowGet); //El JsonRequest Behaviour permite que se devuelva informaciĆ³n de JSON en un getRequest.
}
Consulta7. From this method I make the View:
public ActionResult Consulta7()
{
return View();
}
Finally I need Ajax into the script to read the information pass to method Consulta6. Note: Remember to load the packages json2.js and jquery-3.0.0.js
#{
ViewBag.Title = "Consulta7";
}
<script src="~/Script/jquery-3.0.0.js"></script>
<script src="~/Script/json2.js"></script>
<script type="text/javascript">
$(function () {
$('#btonLista').on("click", function (e) {
e.preventDefault();
$.ajax
({
url: '/Home/Consulta6/',
type: 'get',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
$('#ulLista').append("<li>" + item.consumo + "</li>")
});
}
});
});
});
</script>
<div>
<input type="button" id="btonLista" value="Click" name="" />
<ul id="ulLista"></ul>
</div>
The final result is a page where you click a button and returns the list.
<script type="text/javascript">
$(function ()
{enter code here
$('#btonLista').on("click", function (e)
{
e.preventDefault();
$.ajax
({
url: '/Home/Consulta52/',
type: 'GET',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
$('#ulLista').append("<li>"+item.consumo+"</li>")
});
}
});
});
});
</script>
My two controllers:
public ActionResult Consulta51()
{
return View();
}
public JsonResult Consulta52()
{
var Consulta = new ConsultaContraBD();
var miSegundaConsulta = Consulta.SegundaConsulta();
return Json(miSegundaConsulta.ToList(), JsonRequestBehavior.AllowGet);
}
/// My Sample Starts here
//Controller
namespace Sample.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public JsonResult Consulta52()
{
modelCS model = new modelCS();
List<Department> ds = model.getList();
return Json(ds, JsonRequestBehavior.AllowGet);
}
}
}
//Index.cshtml
#{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
<script src="../../scripts/jquery-2.1.4.js" type="text/javascript">
</script>
<script src="../../scripts/json2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#btonLista').on("click", function (e) {
e.preventDefault();
$.ajax
({
url: '/Home/Consulta52/',
type: 'get',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
$('#ulLista').append("<li>" + item.DepartmentName + "</li>")
});
}
});
});
});
</script>
<div>
<input type="button" id="btonLista" value="Click" name="" />
<ul id="ulLista">
</ul>
</div>
And My Model Class goes like this
public class modelCS
{
string constr = "Data Source=.;Initial Catalog=test1;Integrated Security=True";
List<Department> newDept = new List<Department>();
public List<Department> getList()
{
SqlConnection con = new SqlConnection(constr);
// SqlCommand cmd = new SqlCommand("select * from Department", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from Department", con);
DataSet ds = new DataSet();
da.Fill(ds);
var td = ds.Tables[0];
// List<Department> newDept = new List<Department>();
foreach (DataRow t in td.Rows)
{
newDept.Add(new Department() { DepartmentId = (int)t.ItemArray[0], DepartmentName = t.ItemArray[1].ToString() });
}
return newDept;
//List<string> list = listT
}
}
Department class
public class Department
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
}
Related
I have 4 Views(index view, navigation bar view, Partial view1, partialview2) in One controller
I'd like to switch The Partial View in index view when click navbaritem.
I set LeftPanelPartial in #section.
If I click navbar item, switch ProdFViewPartial() to ProdJViewPartial()
How Can I Get This.
check my code
Controller
namespace DXWMes.Controllers
{
public class ProdController : Controller
{
// GET: Prod
public ActionResult Index()
{
ProdRepository ProdRepo = new ProdRepository();
return View(ProdRepo.GetProdFData("1", "F11", "20220901"));
}
public ActionResult ProdFViewPartial()
{
ProdRepository ProdRepo = new ProdRepository();
return PartialView("ProdFViewPartial",ProdRepo.GetProdFData("1", "F11", "20220901"));
}
public ActionResult ProdJViewPartial()
{
ProdRepository ProdRepo = new ProdRepository();
return View("ProdJViewPartial", ProdRepo.GetProdJData("1", "20220901"));
}
VIEW - Index
#model List<DXWMes.Model.ProdFModel>
#{
ViewBag.Title = "Prod";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Head {
<link rel="stylesheet" type="text/css" href="#Url.Content("~/Content/ProdView.css")" />
<script type="text/javascript" src="#Url.Content("~/Content/ProdView.js")"></script>
}
#section LeftPanelContent {
#Html.Partial("LeftPanelPartial")
}
#section RightPanelContent {
<div class="settings-content">
<h2>Settings</h2>
<p>Place your content here</p>
</div>
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.Partial("ProdFViewPartial")
}
<div id="detailView"> </div>
View - LeftPanelPartial
<h3 class="leftpanel-section section-caption">Production</h3>
#Html.DevExpress().NavBar(navBarSettings =>
{
navBarSettings.Name = "NavBar";
navBarSettings.AllowSelectItem = true;
navBarSettings.ShowGroupHeaders = false;
navBarSettings.Width = Unit.Percentage(100);
navBarSettings.ControlStyle.CssClass = "ProdNavbar";
navBarSettings.Styles.Item.CssClass = "item";
navBarSettings.Groups.Add(group =>
{
group.Items.Add(item =>
{
item.Name = "ProdE1";
item.Selected = true;
});
group.Items.Add(item =>
{
item.Name = "ProdE5";
});
group.Items.Add(item =>
{
item.Name = "ProdF";
});
group.Items.Add(item =>
{
item.Name = "ProdJ";
});
});
navBarSettings.ClientSideEvents.ItemClick = "onProdNavBarItemClick";
}).GetHtml()
JS
(function () {
var selectedIds;
var itemids;
function onProdInit(s, e) {
AddAdjustmentDelegate(adjustProd);
updateToolbarButtonsState();
}
function onProdSelectionChanged(s, e) {
updateToolbarButtonsState();
}
function adjustProd() {
Prod.AdjustControl();
}
function updateToolbarButtonsState() {
var enabled = Prod.GetSelectedRowCount() > 0;
pageToolbar.GetItemByName("Export").SetEnabled(enabled);
}
function onProdNavBarItemClick(s, e)
{
$.ajax({
Url: ' #Url.Action(e.item.name, "Prod")',
type: 'GET',
}).done(funtion(result) {
if(result.redirectTo)
$('#detailView').html(result);
}).fail(function (jqXHR, exception) {
showError(jqXHR);
})
//switch (e.item.name) {
// case "ProdJ"
I have a view component, EventsViewComponent, which is loaded in my Events view index.cshtml using the following lines of code:
<div id="events">
#await Component.InvokeAsync("Events", new { showPrevious = Model.ShowPrevious, showUpcoming = Model.ShowUpcoming })
</div>
I have two checkboxes added like this:
#Html.CheckBoxFor(m => m.ShowPrevious, new { id = "cbShowPrevious", onchange = "ReloadEvents()" })
#Html.CheckBoxFor(m => m.ShowUpcoming, new { id = "cbShowUpcoming", onchange = "ReloadEvents()" })
ReloadEvents() refers to a Javascript function in which I was hoping to refresh the EventsViewComponent with an Ajax call something like:
function ReloadEvents() {
$.ajax({
url: '#Url.Action("ReloadEvents", "Events")',
data: {
showPrevious: document.getElementById("cbShowPrevious").checked,
showUpcoming: document.getElementById("cbShowUpcoming").checked
},
success: DoThis()
})
}
function DoThis() {
const eventsDiv = document.getElementById('events');
eventsDic.innerHTML = //HTML from EventsViewComponent
}
But I don't seem to be able to get the HTML from the EventsViewComponent.
I have written the Default.cshtml for EventsViewComponent like this:
#{
List<Event> events = ViewData["Events"] as List<Event>;
if (events.Count > 0)
{
<table>
//event data from the model
</table>
}
}
The InvokeAsync method in EventsViewComponent is being hit, as is the ReloadEvents method in EventsController but I'm obviously misunderstanding something as I don't seem to be able to update the EventsViewComponent.
Please could someone advise if this is possible and how to go about achieveing it?
To get the HTML from the EventsViewComponent,you need to change like below:
success: function (data) {
$("#events").html(data);
}
Here is a whole working demo like below:
1.Model:
public class Event
{
public bool ShowPrevious { get; set; }
public bool ShowUpcoming { get; set; }
public string Data { get; set; }
}
2.ViewComponent:
public class EventsViewComponent : ViewComponent
{
List<Event> data = new List<Event>() {
new Event(){ ShowPrevious=true,ShowUpcoming=false,Data="aaa"},
new Event(){ ShowPrevious=false,ShowUpcoming=true,Data="bbb"},
new Event(){ ShowPrevious=false,ShowUpcoming=true,Data="ccc"},
};
public IViewComponentResult Invoke(bool showPrevious,bool showUpcoming)
{
if (showPrevious == true && showUpcoming == true)
{
ViewData["Events"] = data;
}
else if (showPrevious)
{
ViewData["Events"] = data.Where(u => u.ShowPrevious == true).ToList();
}
else if(showUpcoming)
{
ViewData["Events"] = data.Where(u => u.ShowUpcoming == true).ToList();
}
return View();
}
}
3.Controller:
public class HomeController : Controller
{
public IActionResult ReloadEvents(bool showPrevious, bool showUpcoming)
{
return ViewComponent("Events", new { showPrevious = showPrevious, showUpcoming = showUpcoming });
}
public IActionResult Index()
{
var model = new Event() { ShowPrevious = true, ShowUpcoming = true };
return View(model);
}
}
4.Index.cshtml:
#model Event
#Html.CheckBoxFor(m => m.ShowPrevious, new { id = "cbShowPrevious", onchange = "ReloadEvents()" })
#Html.CheckBoxFor(m => m.ShowUpcoming, new { id = "cbShowUpcoming", onchange = "ReloadEvents()" })
<div id="events">
#await Component.InvokeAsync("Events", new { showPrevious = Model.ShowPrevious, showUpcoming = Model.ShowUpcoming })
</div>
#section Scripts
{
<script>
function ReloadEvents() {
$.ajax({
url: '#Url.Action("ReloadEvents", "Home")',
data: {
showPrevious: document.getElementById("cbShowPrevious").checked,
showUpcoming: document.getElementById("cbShowUpcoming").checked
},
success: function (data) {
$("#events").html(data);
}
})
}
</script>
}
5.Default.cshtml(the view component Razor view):
#model Event
#{
List<Event> events = ViewData["Events"] as List<Event>;
if (events.Count > 0)
{
<table>
<tr>
<th>ShowPrevious</th>
<th>ShowUpcoming</th>
<th>Data</th>
</tr>
<tbody>
#foreach (var item in events)
{
<tr>
<td>#item.ShowPrevious</td>
<td>#item.ShowUpcoming</td>
<td>#item.Data</td>
</tr>
}
</tbody>
</table>
}
}
Result:
I have implemented such solution in one of my projects, check it out -> Refreshing .Net core MVC ViewComponent over AJAX
Dear Community,
I am facing a problem in redirecting my angular js controller to c# controller.Below is my scrip controller code and c# controller code.Am i making any mistakes in url or is there any routing needed to take my angular controller to c# controller.When the controller is hit,it calls error callback with error alert instantly.please provide me with a solution.
angular controller code:
var httpTimeout = 1800000;
var httpTimeoutSearch = 3600000;
angular.module('MyApp', [])
var app = angular.module('myApp', []);
app.controller('LoginController', ['$scope', '$rootScope', '$http', function ($scope, $rootScope, $http) {
$scope.username = "";
$scope.password = "";
$scope.Login = function () {
if ($scope.username != null && $scope.username != "") {
if ($scope.password != null && $scope.password != "") {
try {
$http({
method: 'POST',
url: '/Account/Maxi',
data: { Username: $scope.username, Passord: $scope.password },
timeout: httpTimeout,
}).then(function successCallback(response) {
alert("sucess");
}, function errorCallback(response) {
alert("error");
});
}
catch (ex)
{ alert(ex); }
}
}
}
}]);
My C# Controller code:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Maxi(LoginModel data, string returnUrl)
{
string strReturn = "";
string ConStr = "";
string Code = "";
if (data.UserName != null)
{
if (data.Password != null)
{
DataSet ds = new DataSet();
SqlParameter[] parameters =
{
new SqlParameter( "#name", SqlDbType.VarChar, 20) { Value = data.UserName } ,
new SqlParameter("#Roll_No", SqlDbType.Int) { Value = data.Password } ,
};
ConStr = "Data Source=" + "192.168.1.9" + ";Initial Catalog=" + "MyFistDataBase" + ";User id=" + "sa" + ";Password=" + "123" + ";";
using (SqlConnection con = new SqlConnection(ConStr))
{
using (SqlCommand cmd = new SqlCommand("Maxi", con))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
cmd.Parameters.AddRange(parameters);
da.SelectCommand = cmd;
da.Fill(ds);
}
}
string errmsg = "";
if (errmsg != "")
{
Code = "0"; strReturn = errmsg;
}
else
{
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
Code = "1";
foreach (DataRow dr in ds.Tables[0].Rows)
{
strReturn += dr[0].ToString();
}
if (strReturn == "1")
{
Console.Write("Updated");
}
}
//TripDT = TripDT.ToShortDateString();
}
}
}
}
return View(data);
}
first this first you need to correct your spelling mistakes in code that is BIG mistake in programming.
Try this type of data
C# class like this
public class EmployeeInfo
{
[Key]
public int EmpNo { get; set; }
public string EmpName { get; set; }
public decimal Salary { get; set; }
}
js object like this
var Employee = {
EmpNo: $scope.EmpNo,
EmpName: $scope.EmpName,
Salary: $scope.Salary,
};
http part change like this
$http({
method: "post",
url: "/Account/Maxi",
data: Employee
}).then(function successCallback(response) {
alert("sucess");
}, function errorCallback(response) {
alert("error");
});
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Maxi(EmployeeInfo emp)
{
your code here
}
hope this will help you
I would like to know how to convert the following object to C# when reaching the mathod. I needed to create an object which can hold multiple array's within JSON something like the following
{
"cars": {
"Ferrari":["LaFerrari","F40","458"],
"Porsche":["911","959"],
"Lamborghini":["Aventador"]
}
}
The code I used is the following within cshtml
<div class="row">
<div class="col-md-4">
<div>
<input type="text" id="txtKey" />
<input type="button" id="btnKey" />
</div>
<div>
<input type="text" id="txtChild" />
<input type="button" id="btnChild" />
</div>
<div>
<input type="button" id="btnSubmit" />
</div>
</div>
</div>
#section scripts
{
$(function () {
AddKeyToDictionary('Ferrari');
AddKeyToDictionary('Porsche');
AddKeyToDictionary('Lamborghini');
AddValueToDictionary('Ferrari', 'LaFerrari');
AddValueToDictionary('Ferrari', 'F40');
AddValueToDictionary('Ferrari', '458');
AddValueToDictionary('Porsche', '911');
AddValueToDictionary('Porsche', '959');
AddValueToDictionary('Lamborghini', 'Aventador');
$('#btnKey').click(function () {
AddKeyToDictionary($('#txtKey').val());
});
$('#btnChild').click(function () {
AddValueToDictionary($('#txtKey').val(), $('#txtChild').val());
});
$('#btnSubmit').click(function () {
submit();
});
});
var dict = {};
function AddKeyToDictionary(key) {
dict[key] = [];
}
function AddValueToDictionary(key, value) {
dict[key].push(value);
}
function submit() {
var url = "#Url.Action("UpdateCustomFields", "Home")";
var data = JSON.stringify({ 'cars': dict });
$.ajax({
type: "POST",
contentType: "Application/json;charset=utf-8",
url: url,
data: data,
datatype: "json",
success: function (msg) {
},
error: function (request, status, error) {
displayDialog("A communication Error has occurred, please contact IT support: " + error);
}
});
}
</script>
}
I've tried the following within MVC (got this from a JSON c# convertor)
public JsonResult UpdateCustomFields(RootObject cars)
{
return Json("");
}
}
public class Cars
{
public List<string> Ferrari { get; set; }
public List<string> Porsche { get; set; }
public List<string> Lamborghini { get; set; }
}
public class RootObject
{
public Cars cars { get; set; }
}
The car makes should be dynamic and then the arrays below should be converted correctly.
I also tried to iterate through the array and changed them all to key value pairs which still wasn't rendering
function convertToKeyValue() {
submitValue = [];
for (var k in dict) {
if (dict.hasOwnProperty(k)) {
if (dict[k].length > 0) {
for (var i = 0; i < dict[k].length; i++) {
submitValue.push({ key: k, value: dict[k][i] });
}
} else {
submitValue.push({ key: k, value: '' });
}
}
}
}
Passing them through the name/value pairs I was able to see them in the dynamic property within the controller but can't get to the variables.
public JsonResult UpdateClientCustomFields(object cars)
{
var result = customFields.XmlSerializeToString();
return Json("hello");
}
If anyone can help or point me in the right direction.
Thanks
Updated: I've had to convert the javascript array to a list of key pairs (not ideal) and use List> cars as the paramter, the model is not ideal, but will use this until I find a better way.
Here is the updated code
HTML
<input type="button" id="btnSubmit2" />
var submitValue = [];
function convertToKeyValue() {
submitValue = [];
for (var k in dict) {
if (dict.hasOwnProperty(k)) {
//alert("Key is " + k + ", value is" + dict[k]);
//alert("KEY: " + k);
if (dict[k].length > 0) {
for (var i = 0; i < dict[k].length; i++) {
//alert("childrec: " + dict[k][i]);
submitValue.push({ key: k, value: dict[k][i] });
}
} else {
submitValue.push({ key: k, value: '' });
}
}
}
}
function submit2() {
convertToKeyValue();
var url = "#Url.Action("UpdateCustomFields2", "Home")";
var data = JSON.stringify({ 'cars': submitValue });
$.ajax({
type: "POST",
contentType: "Application/json;charset=utf-8",
url: url,
data: data,
datatype: "json",
success: function (msg) {
},
error: function (request, status, error) {
}
});
}
MVC
public JsonResult UpdateCustomFields2(List<Dictionary<string, string>> cars)
{
return Json("");
}
Try changing your cars property in RootObject to public Dictionary<string,List<string>> cars {get; set;}
Try to make your input param as string and then deserialize it to your object.
public JsonResult UpdateCustomFields(string cars)
{
RootObject yourCars = JsonConvert.DeserializeObject<RootObject>(cars);
return Json("");
}
Good luck :)
Unless I am missing something, the following seems to work fine
public class Program
{
public void Main(string[] args)
{
var json = #"
{
""cars"": {
""Ferrari"":[""LaFerrari"",""F40"",""458""],
""Porsche"":[""911"",""959""],
""Lamborghini"":[""Aventador""]
}
}
";
var dataObj = JsonConvert.DeserializeObject<Data>(json);
}
public class Data
{
public Dictionary<string, List<string>> Cars { get; set; }
}
}
Which version of JSON.NET are you using? I remember older versions had issues with dictionaries, but you could probably just create your own converter if that is the case.
I will display a view, when I click on checkbox
I tried like this, but not work,
I need your help to fix the problem
Models:
public class DisplayData
{
public bool ID { get; set; }
public DisplayData(bool ID)
{
this.ID = ID;
}
}
public class Element
{
public string Descripcion { get; set; }
}
HomeController:
public ActionResult Index()
{
DisplayData Display = new DisplayData(false);
return View(Display);
}
Index.cshtml:
#model AppTwitter.Models.DisplayData
<script src="#Url.Content("~/Scripts/myCheckbox.js")" type="text/javascript"></script>
#Html.CheckBoxFor(
x => x.ID,
new {
data_url = Url.Action("PartialDemo", "PartialDemo"),
id = "mycheckbox"
}
myCheckbox.js:
$(function () {
$('#mycheckbox').change(function () {
var data = {};
data[$(this).attr('name')] = $(this).is(':checked');
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: data,
success: function (result) {
}
});
});
});
PartialDemoController.cs
public ActionResult PartialDemo()
{
var element = new Element();
element.Descripcion = "Descripcion";
return View(element);
}
PartialDemo.cshtml:
#model AppTwitter.Models.Element
<div class="editor-label">
#Html.LabelFor(model => model.Descripcion )
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Descripcion )
#Html.ValidationMessageFor(model => model.Descripcion )
</div>
Thanks,
#Victor, Now i got the issue. The id that you are assigning to checkbox doesn't get worked because you are using #Html.CheckBoxFor(x => x.ID). in this case the id of checkbox is generating dynamically hence "mycheckbox" doesn't get worked. So Instead assigning a id assign a class i.e
#Html.CheckBoxFor(
x => x.ID,
new {
data_url = Url.Action("PartialDemo", "PartialDemo"),
#class = "mycheckbox"
}
)
and in javascript use below:
$(function () {
$('.mycheckbox').click(function () {
// your existing stuff
});
});
Hope this will solve the problem