Trigger button click after view got loaded - c#

In my old MVC application, I have a login button once the application main page got loaded I have to explicitly click on login to get into the application. Now I would like to trigger the login_btn click event after my view got loaded via code.
In Jquery called the login_btn trigger event in document.ready function, and in controller I used viewBag option. Which is the best way to achieve
In jquery,
$(document).ready(function () {
$('#login_btn').trigger('click');
});
Its getting called when the page get refreshed.
In controller viewBag
public IActionResult Index(string info)
{
loginModel myModel = new loginModel();
test(); //tried
return View(myModel);
}
public void test()
{
ViewBag.JavaScriptFunction = "login()";
}
gives error login not defined, because before loading the model I am calling the test()
Provide me some info on how to trigger the login automatically after the view page got loaded.

Modifying my original answer, the solution using a flag to control the auto-login would be:
if( alreadyLoggedFlag === false ) {
alreadyLoggedFlag = true;
$('#login_btn').trigger('click');
}

Related

Switching between two partial views in a layout

I have two partial views that I want to load after clicking a button. It should work like this - the first partial view is the one that displays defaultly, after I click the button - the partial view switches to the second one. Once you click again on the same button in the partial view - the layout switches to the first one. I don't really know how to approach that problem - I thought about declaring a flag that would go from 0 to 1, but I couldn't figure out how to save that flag in a controller or in a .cshtml page so that it saves even if I refresh the page. The two partial views show in every page of my app - it's a sidebar.
Code snippet of my _layout.cshtml
<div class="container-fluid">
<div class="row">
#{
int flag = Convert.ToInt32(HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"]);
if (flag == 1)
{
Html.Action("LoadPartial", "Home");
}
else
{
Html.Action("LoadPartial2", "Home");
}
}
}
</div>
</div>
Controller snippet
public PartialViewResult LoadPartial()
{
var context = new ApplicationDbContext();
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
var user2 = userManager.FindById(User.Identity.GetUserId());
AspNetUser model = new AspNetUser();
model.Email = user2.Email;
model.Id = user2.Id;
model.UserName = user2.UserName;
model.PhoneNumber = user2.PhoneNumber;
return PartialView("_ProfileEditPartial", model);
}
You could try saving the flag as a session value, the following link shows Mircosoft's documentation on how to set up session state: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-3.1#session-state. Once set up, you can easily set/get your value using
HttpContext.Session.SetInt32("SessionPartial", 0);
HttpContext.Session.GetStringInt32("SessionPartial");
and it stays persistent even if user refreshes. Since you said the partials show up on every page of the app, set the session variable in the first controller method your app goes into, or as early as possible.
After setting up the session variable, create a controller method which determines what partial to return based on the session value.
public PartialViewResult LoadPartial()
{
var flag = HttpContext.Session.GetInt32("SessionPartial");
if (flag == 0) {
// set up model here
return PartialView("_Partial1", model);
}
else {
// set up model here
return PartialView("_Partial2", model);
}
}
Finally, in the view write some JavaScript in which you simply get and display the partial. On the click of the button, get the div in which your partial is stored, empty it of the past partial, and then load the correct partial by calling the controller method.
$(document).ready(function() {
$("#buttonId").click(function () {
$('#divId').empty();
$('#divId').load('#Url.Action("LoadPartial", "<YourControllerNameHere>"));
});
}

C# MVC 5 - How To Get a Table In a Partial View

I'm trying to make a HTML table with a checkbox column where this checkbox column is from a ViewModel:
public string FirstName ...
public string LastName ...
public bool Checked ...
I want to get the List<ViewModel> and pass it to the controller, using a Partial View, to verify the checked columns, because I want to delete the checked lines.
If I wanted to get the checked columns in the same controller, I do, but in a different controller, I don't. In my case, this 'Partial View' is a BS Modal.
What you need is a partial rendered through Ajax. You call the action method from a modal using load and POST the form data so it removes checked lines. You can call any controller you need from this, all you need is:
$('#target').load('#Html.Url("Action", "Controller")');
And on submit:
$('#targetform').submit(function (e) {
var data = JSON.stringify($(e.currentTarget).serialize());
$.post('#Html.Url("Action", "Controller")', data, function (html) {
$('#target').html(html);
});
e.preventDefault();
});

Binding client side event to dyanamic datalist items using jquery

I got stuck in a problem. I am loading elements in a datalist dynamically. and i am trying to bind click event on a column using jquery. It works fine when i use master page with it. as it follows the page life cycle and loading jquery after child page data binding. But when i use it in a normal page(without master page) it does not allow me to perform desired action. I know why is this happening, the reason is jquery is being loaded before elements binding. so jquery is not able to bind click event since it is not able to find those controls.
binding elements already have "item" class in them
here is my jquery code:
$(document).ready(function () {
$('.item').click(function () {
//do something here
});
});
code behind:
protected void Page_Load(object sender, EventArgs e)
{
using (TestEntites db = new TestEntites())
{
IEnumerable<Template> Test = from t in db.Template
where t.Customer == clsuser.CustomerID
&& t.Region == user.RegionID
select t;
dlTemplateGroups.DataSource = Test;
dlTemplateGroups.DataBind();
BindTemplates(db);
}
}
$(document).ready(function () {
$('body').on('click', '.item' ,function () {
//do something here
});
});
$('body') make it more specific based on your html
I also had the same problem once and this problem really is a pain.
Here is my solution:
Instead of binding with click create a function for example:
function reBinding()
{
$('.item').on("click",function () {
//do something here
});
}
and call this function after data binding is done. it will be good if you are using update panel.
ScriptManager.RegisterStartupScript(rptGridAlbum.GetType, "scriptname", "reBinding();", True)

Event not firing on button click event

This is a problem I haven't come across before.
I'm working on an MVC4 project. I'm using an asp button control because there isn't a Html Helper that can be used for a button (re: There's no #Html.Button !). My button code is:
<td><asp:Button ID="ButtonUndo" runat="server" Text="Undo"
OnClick="ButtonUndo_Click" AutoPostBack="true"/></td>
I went to the Designer tab and clicked on this button which produced the event handler:
protected void ButtonUndo_Click(object sender, EventArgs e)
{
RRSPSqlEntities db = new RRSPSqlEntities();
int id = (int)ViewData["ClientId"];
var updateAddress = (from a in db.Address
where a.PersonId == id
select a).SingleOrDefault();
updateAddress.Deleted = false;
db.SaveChanges();
}
I should add that this code was added to the same .aspx page wrapped in a script tag. Also within this section is the Page_Load method. The eventhandler is not within Page_Load.
The problem was found when I set a breakpoint and stepped through the code. Clicking my button shows that it doesn't hit my event handler at all. I don't know why this is, particularly as ASP created the event from clicking the button in Design mode.
Clicking my button shows that it doesn't hit my event handler at all.
This isn't all that surprising. ASP.NET MVC uses a completely different event model (i.e. it doesn't have one like web forms). However, what you're trying to do is very straight forward. In your controller build a new method, let's call it Undo:
public ActionResult Undo(int id)
{
RRSPSqlEntities db = new RRSPSqlEntities();
var updateAddress = (from a in db.Address
where a.PersonId == id
select a).SingleOrDefault();
updateAddress.Deleted = false;
db.SaveChanges();
return View("{insert the original action name here}");
}
and then in your markup, simply markup the input like this:
<form method="POST" action="/ControllerName/Undo">
#Html.HiddenFor(Model.Id)
<input type="submit" value="Undo" />
</form>
where the Model for the View you're on contains a property, I've called it Id, that is the id you want passed into Undo.
I usually prefer to make ajax calls. You can try:
<button type="button" class="button" onclick="ButtonUndo();" />
In the form:
<script>
function ButtonUndo() {
$.ajax({
type: 'POST',
url: '/controller/action',
data: 'PersonID=' + ID,
dataType: 'json',
cache: false,
success: function (result) {
//do stuff here
},
error: function () {
//do error stuff here
}
});
}
</script>
Controller:
[HttpPost]
public ActionResult Action(int PersonID)
{
//Do your stuff here
return new JsonResult { result = "something" };
}
(Sorry for any typos or syntax errors...I pulled from existing code that we use in a project.)

Devexpress 12.1 MVC GridView Inside Tab Strip Issues

I'm an intern that has never done any web development just so you know where I'm coming from. I'm currently trying to learn asp.NET MVC 3 using devexpress 12.1 tools. I started with a template that had a devexpress gridview in the content area that is linked up to the Northwind db. It works by itself, but when I create a devexpress tab strip and place the gridview inside the second tab I get the column headings, but no data is displayed. When I click on a column heading to sort the data shows up. I'm wanting the gridview to load after I click the tab and not when the page loads. Maybe my callbacks are the problem. My tab strip is using an ajax callback and the gridview is as well for the paging. I have added the model to the TabControlPartial page and passed in the model in the controller for the TabControlPartial action. I've tried looking at the demos at mvc.devexpress.com, but there is nothing that puts the two together. I don't 100% understand passing the model into the view I guess. I know this is simple, but I don't know what to do. Thanks for your help.
Controller (this may be my issue):
public ActionResult LookUp()
{
return View(NorthwindDataProvider.GetCustomers());
}
public ActionResult _TabControlPartial()
{
return PartialView("_TabControlPartial", NorthwindDataProvider.GetCustomers());
}
public ActionResult _GridViewPartial()
{
return PartialView("_GridViewPartial", NorthwindDataProvider.GetCustomers());
}
LookUp View (Index):
#model System.Collections.IEnumerable
#Html.Partial("_TabControlPartial", Model)
Tab Partial:
#model System.Collections.IEnumerable
#Html.DevExpress().PageControl(
settings =>
{
settings.Name = "TabControl";
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.Height = System.Web.UI.WebControls.Unit.Percentage(100);
settings.CallbackRouteValues = new { Controller = "Customers", Action =
"_TabControlPartial" };
settings.TabPages.Add(
tabOne =>
{
tabOne.Name = "TabOne";
tabOne.Text = "Start";
tabOne.SetContent(() =>
{
ViewContext.Writer.Write("Start");
});
});
settings.TabPages.Add(
tabTwo =>
{
tabTwo.Name = "TabTwo";
tabTwo.Text = "Customer List";
tabTwo.SetContent(() =>
{
Html.RenderPartial("_GridViewPartial", Model);
});
});
}).GetHtml()
GridView Partial:
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "GridView";
settings.CallbackRouteValues = new { Controller = "Customers", Action =
"_GridViewPartial" };
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.Height = System.Web.UI.WebControls.Unit.Percentage(100);
settings.SettingsPager.Visible = true;
settings.SettingsPager.PageSize = 15;
settings.ControlStyle.Paddings.Padding = System.Web.UI.WebControls.Unit.Pixel(0);
settings.ControlStyle.Border.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(0);
settings.ControlStyle.BorderBottom.BorderWidth =
System.Web.UI.WebControls.Unit.Pixel(1);
//Configure grid's columns in accordance with data model fields
settings.Columns.Add("ContactName");
settings.Columns.Add("Address");
settings.Columns.Add("City");
settings.Columns.Add("PostalCode");
settings.Columns.Add("Phone");
}).Bind(Model).GetHtml()
You're missing the data in the GridView when the tab is opened. When you open the page, the data for the GridView needs to be loaded in the Model that is returned. right now you load the page (in LookUp), but you aren't pushing the data for the grid. whenever any callback occurs, only at that point is the data getting pulled from the database and returned to the screen (notice you only return data in the Callback methods _TabControlPartial and _GridViewPartial). When you sort a column, or filter, etc, then the callback is fired and the data is returned from the server.
The code you have looks correct, but somewhere in the process the Model is losing it's value. the best option is to put a breakpoint in the tab control, the Grid Binding, and the controller and make sure the data you expect is in place when it's bound.
You could "cheat" by putting in a callback when the tab is activated such as:
#Html.DevExpress().PageControl(
settings =>
{
settings.Name = "TabControl";
settings.ClientSideEvents.Init = "TabControl_Init";
...
}).GetHtml()
and in JavaScript have:
function TabControl_Init(s, e) {
GridView.PerformCallback();
}
this way, after the tabs are initialized, the GridView will run a callback, and grab the data correctly. But it would be better to figure out why the data isn't being sent down in the first place by stepping through the code.

Categories