I went through many links: How to reload the current route with the angular 2 router, but I did not get working solution for me.
I have the edit screen, through Edit Screen I can add student, when I successfully added student, I should be able to see newly added Student in the same screen. Is there any way if we can do this? I am using Angular 7.
addStudents(): void {
this.student.studentId = this.studentId;
console.log(this.student);
this.studentService.saveStudent(this.student).subscribe(response => {
console.log(response);
this.memberResponse = response;
});
this.ngOnInit();
this.router.navigate(['/student-edit', this.studentList]);
}
If you want to use the same screen then why do you need to change the route? or reload the page?
You can do it by boolean only
Like this
Your ts file
export class myComponent {
isEditMode = true;
addStudents(): void {
this.student.studentId = this.studentId;
this.studentService.saveStudent(this.student).subscribe(response => {
this.memberResponse = response;
isEditMode = false;
});
}
}
Now in Html
<div *ngIf="isEditMode">
// HTML for edit screen
</div>
<div *ngIf="!isEditMode">
// HTML for view students screen
</div>
HTML
<div *ngIf="edit">
// edit student form
</div>
<div *ngIf="!edit">
// show all student table
</div>
TS File
openEditForm() { this.edit = true } // When user want to edit or add student
// Called when user clicks save on Edit Form
onSaveButtonClick() {
// Logic to save or edit student using subscription
}
1 . On successful execution of Saving or editing student call the API to GetAllStudents
On successful execution of GetAllStudents set "this.edit = false"
Related
In my web app I have a grid list. I select a row and then click the edit button to show a partial update view (which I use to add new data too) in a popup window. The view shows, but I don't have any values in the textboxes. I use devextreme components, but I think, my issue has nothing to do with it (maybe I'm wrong).
This is the onClick code:
function editrow_onClick() {
var key = $("#grid").dxDataGrid("instance").getKeyByRowIndex(selectedRowIndex);
$.ajax({
url: '/MasterData/Sender/UpdateSender/'+key,
}).done(function (response) {
var popup = $("#sender-popup").dxPopup("instance");
popup.option("contentTemplate", function (content) {
content.append(response);
});
popup.show();
});
}
If I click the edit button, I get the right url like /MasterData/Sender/UpdateSender/3.
The corresponding controller action looks like this:
[Route("{id}")]
public IActionResult UpdateSender(long SenderId)
{
return PartialView("NewSender", SenderRepository.GetSender(SenderId));
}
On top of the controller class I have the corresponging attribute: [Route("MasterData/[controller]/[action]")]
I testet id, the action is reached, but the SenderId is 0. I would expect f.e. 3. This should be causing the empty view, I think. Why is SenderId 0 (the default value)?
I post the update view too, maybe this is the source of the problem (don't bother the AddSender action, I plan to change it conditionally, if I get the update data working):
#model Sender
<form asp-action="AddSender" asp-controller="Sender" method="post">
#using(Html.DevExtreme().ValidationGroup()) {
#(Html.DevExtreme().Form<Sender>()
.ID("form")
.ColCount(1)
.Items(items => {
items.AddSimpleFor(m => Model.Name);
items.AddSimpleFor(m => Model.Address);
items.AddSimpleFor(m => Model.ContactPerson);
items.AddSimpleFor(m => Model.ContactEmail);
items.AddGroup().Items(groupItem => groupItem.AddSimple().Template(
#<text>
<div style="text-align: right">
#(Html.DevExtreme().Button().ID("save").Text("Mentés").Width(100).Type(ButtonType.Success).UseSubmitBehavior(true))
#(Html.DevExtreme().Button().ID("cancel").Text("Mégsem").Width(100).Type(ButtonType.Normal).OnClick("close_onClick"))
</div>
</text>));
})
.LabelLocation(FormLabelLocation.Top)
.FormData(Model)
)
}
</form>
<script>
function close_onClick() {
$("#sender-popup").dxPopup("hide");
}
</script>
[Route("{SenderId}")] public IActionResult UpdateSender(long SenderId) { return PartialView("NewSender", SenderRepository.GetSender(SenderId)); }
Try replacing id with SenderId.
Then action method will hit with the desired value.
I'm an MVC noob so bear with me, I'm used to working with web forms. I have a page where administrators can view all users. Right now it shows ALL users, inactive and active. I can make it show only active users by default, but I would like to have a checkbox that can be clicked in order to show inactive users. I want the change to occur as soon as the box is checked or unchecked.
In the view:
#Html.CheckBox("ShowInactive") <label for="inactvCheckBox">Show Inactive Users</label>
In the controller:
public ActionResult Index(bool ShowInactive)
{
var users = (ShowInactive) ? db.Users.OrderBy(u => u.LastName) :
db.Users.Where(u => u.Active == 1).OrderBy(u => u.LastName);
return View(users.ToList());
}
Obviously the way I'm doing it doesn't work, but I'm not sure what I'm missing. Index isn't receiving the value of ShowInactive and I get a null parameter entry error.
EDIT: apparently I need some javascript to handle the click event, and then pass the checkbox state to the controller; I guess I thought it would automatically link with the parameter name being the same. I tried adding the following javascript below, but it doesn't work. Again, I've probably written it wrong but my Google-fu is failing.
<script type="text/javascript">
$(document).ready(function () {
$('#ShowInactive').change(function () {
$("form").attr("Index", "/User/Index");
$("form").submit();
});
});
</script>
Alright, I figured it out. I didn't actually need to handle anything through the controller, I just loaded all users to the list and then added a hidden class to users who weren't active. Then upon checkbox click I toggled the hidden rows using javascript. It's quicker than reloading the view every time I click the checkbox. Only problem is it messes up alternating row colors when inactive users are hidden, but this page is only looked at by site admins so no big deal.
Controller:
public ActionResult Index()
{
var users = db.Users.OrderBy(u => u.LastName);
return View(users.ToList());
}
View:
#Html.CheckBox("ShowInactive", false, new { id = "ShowInactive" }) <label>Show Inactive Users</label>
[...]
#foreach (var item in Model.OrderBy(u => u.LastName).ThenBy(u => u.FirstName))
{
<tr #if(item.Active != 1) { <text>class="inactive hidden"</text>}>
[row data stuff]
</tr>
}
Javascript in view:
<script type="text/javascript">
$(document).ready(function () {
$('#ShowInactive').change(function () {
$(".inactive").toggleClass("hidden");
});
});
</script>
Change the checkbox to:
#Html.CheckBox("ShowInactv")
Thereby matching the parameter of your Action.
I am using one controller which is inserting values in the database. I want to display alert message from controller when the values insertesd in the database successfully.
Is it possible. If yes then how?
You can add the result to ViewData. For example:
if (SaveToDbOK)
{
ViewData["Success"] = "Data was saved successfully.";
// Do other things or return view
}
In your view you can place anywhere:
MVC2:
<% if (ViewData["Success"] != null) { %>
<div id="successMessage">
<%: ViewData["Success"] %>
</div>
<% } %>
MVC3:
#if (ViewData["Success"] != null) {
<div id="successMessage">
#ViewData["Success"]
</div>
#}
I used this approach in my last project in order to make the information returned from the server unobtrusive. Checking whether ViewData["Success"] or ViewData["Failure"] are done in the Master page, the divs are formatted using CSS, jQuery code was used to hide the notifications after 5 seconds.
Regards,
Huske
public ActionResult UploadPropertyImage()
{
// Business logic....
return Content("<script language='javascript' type='text/javascript'>alert('Save Successfully');</script>");
}
Basically that depends on how are you inserting the value into the database, as you would need a method to tells you whether the insertion was successful. As there's a few ways to do that now, linq/entity framework/sql/etc.
Then after you know whether did the insertion happens, then you can just assign a value to a variable and then from the code/aspx just check the value and do a simple alert.
<script type="text/javascript">
//i'm using jquery ready event which will call the javascript chunk after the page has completed loading
$(document).ready(function(){
//assuming that your variable name from the code behind is bInsertSuccess
var bSuccess = "<%= bInsertSuccess %>";
if(bSuccess){
alert("Successfully Inserted");
}
});
</script>
You may add below code to tell user
Return Content("Data added successfully");
I have created an Ajax.BeginForm, which based on a value in a dropdown menu, should either post values to an actionresult or open a modal pop-up window which would contain a list of checkbox items and a submit button. This is what i have at the moment:
<div class="examplepanel">
#using (Ajax.BeginForm("PostExample", new AjaxOptions() { UpdateTargetId = "ExamplePopupContainer", HttpMethod = "Post" }))
{
<p>
#Html.Label("Exampletype: ", "ExampleTypes", "LabelTitle")<br />
#Html.DropDownListFor(m => m.ExampleTypes, Model.ExampleTypes, new { #id = "ExampleType" })
</p>
<p>
#Html.Label("Example comments: ", "ExampleComments", "LabelTitle")<br />
#Html.TextAreaFor(m => m.ExampleComments, Model.ExampleComments)
</p>
<p>
#Html.SubmitButton("Confirm", 0, "button")
</p>
}
</div>
So the Actionresult could be:
[HttpPost]
public ActionResult PostExample(string ExampleTypes, string ExampleComments)
{
...
}
Any ideas/example of how I could go about this would be greatly appreciated.
Thanks.
Below steps might be helpful..
1.Bind the on change event of the dropdown (I hope you are building MVC app with jquery)
$("#ExampleType").change(function(e){
//TODO: Client Business Logic
});
2.List down the cases which will be responsible for opening jquery dialog/pop up window.
Use jquery dialog or other jquery plugin for opening popup.
Use below syntax for opening a popup window.
$(<popup control id>).dialog('open')
3.List down other cases which are responsible for posting data to the action (server).
Use jquery ajax for posting data to the server
Use below syntax for posting data to the server.
$.post()
Pseudo code:
$("#ExampleType").change(function(e){
var list_Of_Values_For_Opening_Popup_Window = ['value1','value2']; // or array of integers
var value = $("OPTION:selected", $(this)).val();
var is_Need_To_Post_Data = true;
for(var i=0;i<list_Of_Values_For_Opening_Popup_Window .length;i++)
{
if(value==list_Of_Values_For_Opening_Popup_Window[i])//use case sensitive comparison if required.
{
is_Need_To_Post_Data =false;
break;
}
}
if(is_Need_To_Post_Data )
{
//TODO: Post data to server with ajax call
}
else
{
//TODO: open popup window
}
});
ASP.NET MVC
I have one page Index.aspx where I'm loading two usercontrols into divs. This is working fine. For the moment the usercontrols just shows data and thats working fine. But now I want to add a delete function in the usercontrols and then refresh the div in the Index.aspx page. Is this possible?
Index.aspx
<!-- Panel One -->
<div id="panel1">
<img src="/Content/ajax-loader.gif" alt="Loading..." />
</div>
<script type="text/javascript">
$('#panel1').load('../Reports/ReportOne')
</script>
<!-- Panel Two -->
<div id="panel2">
<img src="/Content/ajax-loader.gif" alt="Loading..." />
</div>
<script type="text/javascript">
$('#panel2').load('../Reports/ReportTwo')
</script>
ReportOne.ascx and ReportTwo
Just listing some data with a foreach. Here I want to add a deletebutton for each item in the lists.
Make your "delete" action into something like this:
[AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
public ActionResult Delete(int id) {
try {
// do what ever here in deleting the record etc
// ...
return null;
} catch (Exception ex) {
TempData[TempDataKeys.ErrorMessage] = "Error in deleting: " + ex.Message;
return RedirectToAction("List");
}
}
In you ascx/aspx, create a jQuery method to wrap your ajax call to the controller:
function deleteRecord(recordId) {
if (confirm("Are you sure that you want to delete this record?")) {
var token = $("input[name='__RequestVerificationToken']")[0].value;
url = '<%= Url.Action("Delete", "MyController") %>';
$.post(
url,
{ id: recordId, __RequestVerificationToken: token },
function(data) {
if (!data == "") {
// success - reload/refresh panel control
$('#panel1').load('../Reports/ReportOne');
} else {
// failed - handle error
}
}
);
}
}
You will need to put your AntiForgeryToken appropriately so the script can access it - you only need 1 for the whole page. Your delete link should then call to the javascript, instead of to the action in the controller directly:
Delete
When the user clicks on the delete button inside the user control you could invoke an action that will delete the necessary information from the database and return a partial view refreshing the control. So put a delete link inside the control:
<%= Html.ActionLink("Delete", "DeleteReportOne", null, new { id = "deleteReportOne" }) %>
and then inside the main page register the click callback for this link:
$(function() {
$('#deleteReportOne').click(function() {
$('#panel1').load(this.href);
});
});
You may use JQuery UI tabs to add and remove the content from the page
JQuery UI Manipulate tabs
JQuery Tabs and ASP.NET MVC Partial Views
you need to modify your user controls