when clicked navbar, how to switch partial view in other view - javascript

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"

Related

DataTable replicating rows

I have a panel where I take data from a view in database, and show them. The data are being showed but it is being replicated 3 times, I mean, each row apears 3 times in my table (panel).
When I use my filters, the data apears only one time though, as it should be.
I thought that I was calling my function "criarDataTables()" 3 times, but this is not the case.
This is in my Index.cshtml:
#section Scripts{
#Scripts.Render("~/bundles/typeahead")
#Scripts.Render("~/bundles/datatables")
#Scripts.Render("~/Scripts/js/bootstrap-datapicker.js")
#Scripts.Render("~/Scripts/js/bootstrap-datepicker.pt-BR.js")
#Scripts.Render("~/Scripts/jQuery-Mask/jquery.mask.min.js")
<script type="text/javascript">
var tbPainelTriagem;
var reload = false;
function criarDataTables() {
tbPainelTriagem = $("#tb-triagem").DataTable({
searching: false,
processing: true,
serverSide: true,
ajax: {
url: "/PainelTriagem/ListaPainelTriagem",
type: "POST",
data: {
customSearch: {
[...]
}
}
},
columns: [
{ data: "ID_VIEW" },
{ data: "TIPO" },
[...]
],
columnDefs: [
],
drawCallback: function (settings, json) {
$("#frm-filtro :input").prop("disabled", false);
}
});
}
$(document).ready(function () {
var listaDs;
$('#dsUnidIntField').attr("autocomplete", "off");
$('#dsUnidIntField').typeahead({
name: 'resultDs',
limit: 200,
minLength: 0,
source: function (query, process) {
itens = [];
listaDs = {};
$.post('/PainelTriagem/DsAutocomplete', { query: query }, function (data) {
$.each(data, function (i, item) {
listaDs[item.Nome] = item;
itens.push(item.Nome);
});
process(itens);
});
},
updater: function (item) {
var ds = listaDs[item];
$('#ID_VIEW', '#frm-filtro').val(ds);
return ds.Nome;
}
});
criarDataTables();
})
</script>
}
[...]
<table id="tb-triagem" class="table table-striped table-bordered dataTableLayout">
<thead>
<tr>
<th>ID View</th>
<th>Tipo</th>
[...]
</tr>
</thead>
</table>
This is in my PainelTriagemController.cs
using [...]
namespace PainelMV.Controllers
{
public class PainelTriagemController : Controller
{
[...]
[HttpPost]
public ActionResult ListaPainelTriagem(HCDataTableRequest<PainelTriagem> dataTableRequest)
{
try
{
HCDataTableResponse<PainelTriagemViewModel> dataTable = MyPainelTriagemManager
.ToList(dataTableRequest).CastViewModel(x => new PainelTriagemViewModel
{
ID_VIEW = x.ID_VIEW,
TIPO = x.TIPO == null ? " - " : x.TIPO.ToString(),
[...]
});
return Json(dataTable);
}
catch(Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
}
}
And this is in my PainelTriagemStore.cs
using [...]
namespace PainelMV.Data.Store
{
public class PainelTriagemStore : BaseStore<PainelTriagem, AppContext>
{
public PainelTriagemStore(AppContext context): base(context) { }
public HCDataTableResponse<PainelTriagem> ToList(HCDataTableRequest<PainelTriagem> dataTableRequest)
{
try
{
HCDataTableResponse<PainelTriagem> response = new HCDataTableResponse<PainelTriagem>();
var qr = _context.PainelTriagem.AsQueryable();
response.recordsTotal = qr.Count();
int? tipo = dataTableRequest.GetCustomSearchInt("tipo");
string nmPaciente = dataTableRequest.GetCustomSearchString("nmPaciente");
[...]
if (tipo != null)
{
qr = qr.Where(x => x.TIPO == tipo);
}
[...]
response.recordsFiltered = qr.Count();
qr = qr.OrderAndPaging(dataTableRequest);
response.data = qr.ToList();
return response;
}
catch(Exception ex)
{
throw ex;
}
}
}
}

Javascript does not update value of a blazor component

I have a problem where I want to pass the value of a CK editor on to a Monaco editor. I can get the value from Monaco to CK but not the other way around. I can also see the value update while debugging but it does not seem to work somehow.
So what i want is when I type something in the CK editor and I press the button to switch to Monaco to have the value of the CK editor in the Monaco editor
This is the javasciprt :
function CkEditor(id, readonly, dotNetReference) {
CKEDITOR.replace(id, {
customConfig: '../ckeditor/config.js'
});
var editor = CKEDITOR.instances[id];
var editorId = editor.id;
var monacoEditor = document.getElementById("monaco_" + editor.name);
// Hide toolbar while loading
editor.on('loaded', () => {
document.getElementById(editorId + '_top').style.display = 'none';
});
editor.on('instanceReady', () => {
EnableCkEditor(id, readonly);
});
editor.on('change', () => {
var data = editor.getData();
if (data === '') {
data = null;
}
dotNetReference.invokeMethodAsync('EditorHasChanged', data);
});
editor.on('focus', (id) => {
editor.focusManager.focus();
document.getElementById(editorId + '_top').style.display = 'block';
editor.on('afterCommandExec', (event) => {
var commandName = event.data.name;
if (commandName === 'enableMonaco') {
if (monacoIsEnabled === false) {
document.getElementById(editorId + '_contents').style.display = 'none';
monacoEditor.classList.remove('monaco-wrapper');
monacoIsEnabled = true;
}
else {
editor.setData(monacoEditorData.value);
document.getElementById(editorId + '_contents').style.display = 'block';
monacoEditor.classList.add('monaco-wrapper');
monacoIsEnabled = false;
}
}
});
});
editor.on('blur', () => {
if (!monacoIsEnabled) {
document.getElementById(editorId + '_top').style.display = 'none';
}
});
}
function setCkEditorValue(value) {
monacoEditorData.value = value;
}
function CkEditorDestroy(id) {
var editor = CKEDITOR.instances[id];
editor.destroy();
delete editor;
}
function EnableCkEditor(id, readonly) {
var editor = CKEDITOR.instances[id];
if (editor) {
var editId = editor.id;
var editorBody = document.getElementById(editId + '_contents');
if (readonly === true) {
editorBody.classList.add('disabled_class');
}
else {
editorBody.classList.remove('disabled_class');
}
}
}
This is the component where it switches between Monaco and CK :
#inherits MarkupEditorComponent
#Value
<div id="wrapper">
<div class="ck-editor-wrapper">
<CkEditor Value="#Value" ValueChanged="#ValueChanged" Readonly="#Readonly" id="#Id"/>
</div>
<div class="monaco-wrapper" id="monaco_#Id">
<CodeEditor Value="#Value" ValueChanged="#ValueChanged" Readonly="#Readonly"/>
</div>
</div>
This is the CKEditor.razor
#inherits CkEditorComponent
<div id="wrapper">
<div class="ck-editor-wrapper">
<textarea #attributes="AdditionalAttributes"
id="#Id"
class="CssClass"
value="#Value"></textarea>
</div>
</div>
And as last the CKEditor.razor.cs
public class CkEditorComponent : BaseComponent
{
string _id = $"CKEditor{Guid.NewGuid().ToString().ToLower().Replace("-", string.Empty)}";
[Parameter]
public string Value { get; set; }
[Parameter]
public EventCallback<string> ValueChanged { get; set; }
[Parameter]
public bool Readonly { get; set; }
[Parameter]
public IReadOnlyDictionary<string, object> AdditionalAttributes { get; set; }
[Parameter]
public string Id
{
get => _id;
set => _id = value;
}
protected override async Task OnInitializedAsync()
{
await EditorHasChanged(Value);
}
protected override async Task OnParametersSetAsync()
{
await EnableEditor(Readonly);
await base.OnParametersSetAsync();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JsRuntime.InvokeVoidAsync("CkEditor", Id, Readonly, DotNetObjectReference.Create(this));
}
}
[JSInvokable(nameof(EditorHasChanged))]
public Task EditorHasChanged(string data)
{
Value = data;
ValueChanged.InvokeAsync(data);
return Task.CompletedTask;
}
protected override void Dispose(bool disposing)
{
JsRuntime.InvokeVoidAsync("CkEditorDestroy", Id);
base.Dispose(disposing);
}
private async Task EnableEditor(bool enabled)
{
await JsRuntime.InvokeVoidAsync("EnableCkEditor", Id, enabled);
}
}
You might need to invoke StateHasChanged() inside EditorHasChanged(string data). A similar issue here.

Refresh ViewComponent in ASP.Net Core MVC View

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

ASP.NET MVC 5 JsonResult & Ajax - MVC JQuery error

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

checkbox with javascript && jQuery

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

Categories