ASP .Net MVC | How to add subviews in view - asp.net

I have a problem, because of I dont know how to write subview in user dashboard.
Example:
I have a dashboard for logged users and there is path Dashboard/Profile.
Dashboard -controller, Profile - view.
In Profile view I wouldlike to create sections/subviews (I dont know how it is called) named Overview, personal data, change password.
I have a menu on left and I want to get that if I will click "personal data", it will be loaded content with personal datas in the container on the right - but with no reloading all page.
The same situation with clicking "change password", I want to show content of "change password" view on right side - without reloading.
How can I get it ? Could anyone help?
Thanks in advance!

Is this is what you are looking for ?
Partial Views

I would look at returning partial views from controllers and AJAX get requests.
In your controller
public class SomeController : Controller
{
[HttpGet]
public ActionResult SomeAction()
{
// do some stuff
return PartialView();
}
}
In your js scripts
$.ajax({
url: '/Some/SomeAction',
contentType: 'application/html; charset=utf-8',
type: 'GET',
datatype: 'html'
})
.success(function (result) {
$("#container").html(result);
})
.error(function (xhr, status) {
alert("We are having trouble, please try again later");
});
Of course the best way to handle these things is with a front end framework like angular 2 or react.

Related

Calling method from razor page

I have a asp.net core mvc project.
In my layout file, I want to display the name of the currently logged in user, such that the username is displayed in the header. For this, I want to be able to call a function in my homecontroller that does this.
So, I made a simple function taht looks like this in the home controller:
public String GetLoggedInuser()
{
return "garse garsebro";
}
And then I have tried every method I have been able to find. The first couple of methods here are just function suggested around the web, that are simply not available to me:
#HtmlHelper.Action("GetLoggedInuser");
#Html.RenderAction("GetLoggedInuser");
To name a few. Then there is this one, which I can find:
#Html.ActionLink("GetLoggedInuser")
But for this one, my function "GetLoggedInuser" can't be found anywhere.
How do you, in a razor page call a controller function that you can get returned a string from that function and display it?
If you are using Microsoft.AspNet.Identity then below line will do the work post login.
#Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
You can try to use ajax to call action to get the username,and add it to html:
<div id="username">
</div>
#section scripts
{
<script>
$(function () {
$.ajax({
type: "GET",
url: 'GetLoggedInuser',
}).done(function (result) {
$("#username").html(result);
});
})
</script>
}

button in ASP.NET are all post method?

Are all button control has to be post method? or we can set it to get method, for example, I want to see an employee details by giving employeeId and click submit button
There is no difference between GET and POST method. They both provide url and parameters. POST method only have some advantages and some restrictions.
If your button is on form (as in classic asp.net), and there is no javascript handler for this button - only POST method can be here.
If you create jquery code (or pure javascript), that overrides default behaviour of the button, you can select what method use: POST or GET
<script>
$('#button').click(function() {
$.ajax({
url: '....',
data: { ....},
type: 'GET', //or 'POST'
success: function(res) {
//all fine
},
error: function() {
//invalid url or server error
}
};
return false; //to avoid default submit
});
</script>

Accessing div in view from controller

In my layout page I've got this html:
<div id="ajax-loading" class="global-loading-image" runat="server">
<img src="/content/travelbill/img/small-loading-image.gif"/>
</div>
Which is a loading-symbol. I want it to show when my code is doing its business.
I've read on other threads here on Stackoverflow that if you use runat="server", you are supposed to be able to access the div in the controller. Like so:
ajax-loading.Visible = true;
EditTravelBillViewModel model = this.travelBillService.GetTravelBill(travelBillId);
model.StageOfProcess = (int)TravelBillStageOfProcessEnum.APPROVED;
this.travelBillService.Update(model, true);
ajax-loading.Visible = false;
return RedirectToAction("GetTravelBillsPerCompany");
But I get the error that the loading and the ajax do not exist in the current context. What am I doing wrong?
That was in the old ASP.NET pages. In ASP MVC you don't have a ViewState, isPostBack or runat="server" you can pass variables from the controller to the view using ViewBag and ViewData like:
Controller:
ViewBag.Name = "My Name";
ViewData["Name"] = "My Name";
View:
#ViewBag.Name
#ViewData["Name"]
I don't think you need to do that. You can have a action that do the task that you need to get done and with JavaScript request that action via AJAX. You can then with JavaScript show and hide the loading as you wish:
function LoadAjax(containerId, url, params){
//Set loading in container
$(containerId).html('<img src="loading.gif" alt="loading"/>');
//Do the request
$.ajax({
type: 'POST',
dataType: "html",
url: url,
data: params,
success: function(data){
// show response inside container (removes loading)
$(containerId).html(data);
},
error: function( jqXHR, textStatus, errorThrown){
// show error inside container (removes loading)
$(containerId).html(textStatus);
}
});
}
While the page is loading it will display the loading image. You will need Jquery to use my code. Hope it helps.

KendoUI Grid Custom Toolbar Action to delete selected items

I'm trying to add a new Custom Toolbar Action to my Kendo UI Grid but am lost on how to get the desired behaviour.
I need a button that I can click that will invoke an action method and pass in the collection of selected items in the grid so I can do a bulk delete (or some other action against all of the records)
Can anyone help ?
Currently I have: -
.ToolBar(toolbar =>
{
toolbar.Custom().Action("Users_DeleteSelected", "Users").Text("Delete Selected");
})
This invokes my method thus: -
public ActionResult Users_DeleteSelected([DataSourceRequest] DataSourceRequest request)
{
// We need the list of selected UI items *here* so we can delete them - but how
...???
// Just redirect for now, we need to test getting the list of selected items here...
RedirectToAction("Index");
}
So if I have several items "selected" in the grid, I somehow want to invoke a method like the one above (Users_DeleteSelected) and have it get passed in the list of items to delete, then redirect to the Index once the delete is complete.
** This may not just be linked to deleting - there may in future be several other functions that will be required that fit the same method - i.e. "Mark As Complete" on a list of jobs for example.
I'm guessing maybe the DataSourceRequest isn't the way to go and that maybe I need to add some client side code to somehow assemble the list of selected items.
KendoUI is great but I need more examples.
Thanks for your kind replies. We've figured it out with a bit of searching and the like.
Firstly "kudos" to "this post" on the kendoui site as it pointed me in the right direction.
It turns out that this is what we need: -
In the. cshtml file for the grid...
// .... Other grid stuff
.ToolBar(toolbar =>
{
toolbar.Custom().Text("Test Button").Url("#").HtmlAttributes(new { #class = "test-button" });
})
// And then also...
$(document).ready(function () {
$(".test-button").click(testFunction)
})
// And finally
function testFunction(e) {
kendoConsole.log("Items Selected");
e.preventDefault();
var grid = $("#Grid").data("kendoGrid");
var selection = [];
grid.select().each(
function () {
var dataItem = grid.dataItem($(this));
selection.push(dataItem);
}
);
$.ajax({
type: "POST",
url: "Users/Users_DeleteSelected",
data: JSON.stringify({ items: selection }),
dataType: "html",
contentType: "application/json; charset=utf-8",
success: function (form) {
document.open();
document.write(form);
document.close();
}
});
};
Then in the controller we simply have: -
[HttpPost]
public ActionResult Users_DeleteSelected(List<UserViewModel> items)
{
// Stub to redirect for now
return RedirectToAction("Index");
}
And that's it. All of the items currently selected in the grid will be posted back to the correct action method and the jobs done.
Thanks.
Sounds like you are looking for batch editing capability. Take a look at this Kendo batch editing example. You can control whether to batch or not on the DataSource.

How to post parameter value to some actionlink

In my view i have 10 link every link associated with some unique value. Now i want that associated value at my controller action and from that action i want to redirect the flow to some other action based on that value.
But the condition is i dont want to display it on url.
How can i acheive this?
I tried ajax.post/#Ajax.ActionLink but doing this will not facilitate redirect to another action.
Is there anything with route i need to do?
View
<ul>#foreach (var item in Model)
{<li>
#Ajax.ActionLink(item.pk_name, "Index","Candidate", new { para1= item.para1 }
, new AjaxOptions { HttpMethod = "POST" })</li>
}</ul>
Action
[HttPost]
public ActionResult(int para1)
{
return RedirectToAction(para1,"anotherController");
}
I am getting value at para1 with ajax post(that is what i primarily needed) but here also want to redirect my application flow base on para1 value which is action name.
Confision : here i am not sure is this is the right way to do this thing. So i am asking you guys should i go for route map of working with ajax post will solve my objective.
If you only need to redirect the user based on what he clicks on without showing him the link, I believe the best way to achieve this is by client-side coding.
In my opinion there is no need to take any request through the server in order to change the page for such a low-complexity redirect.
View
// HTML
// Might be broken, been awhile since I worked with MVC
// Can't really remember if that's how you put variables in HTML
<ul id="button-list">
#foreach(var item in Model)
{
<li class="buttonish" data-para1="#item.para1">#item.pk_name</li>
}
</ul>
// JS
// I wouldn't do any server related work
$('#button-list li.buttonish').click(function(){
// Your controller and action just seem to redirect to another controller and send in the parameter
window.location.href = "/controller/method/" + $(this).data('para1');
});
I think you should make one jQuery function that is call when clicked and pass unique parameter.In that function you can use AJAX and post it on appropriate controller method.
Example:
<input type="button" id="#item.pk_name" onclick="getbuttonvalue(#item.para1);" />
In script
<script type="text/javascript">
$(document).ready(function () {
function getbuttonvalue(para1) {
$.ajax({
cache: false,
type: "POST",
dataType: 'json',
url: "/controller/method/" + para1,
success: function (data) {
}
});
}
});
</script>

Resources