Move from a controller to different views - c#

I created a login page with the built in AccountModel and AccountController. Now I have another controller named TestController that sends data from a database to my TestView.
What I now wish to to is to send the data that I send from the TestController to be displayed within the AccountView.
Basically what I am trying to do is to display a feed on the loginpage at the accountview, problem is that the data comes from my TestController so I do not now how to pass this data.
So I have this:
Controller : AccountController -> Model: AccountModels -> View: Account -> login.cshtml
Controller : TestController -> Model: Compare -> View : Test -> index.cshtml
I wanna display the content from #2 within #1 view. Is this possible?

There are a few ways to do this. I highly recommend looking at the tutorial videos here
You could create an action in your TestController that returns a partial view.
public ActionResult Test()
{
return PartialView("index.cshtml");
}
In your login.cshtml view, you would display the partial view from TestController by calling #Html.Action("Test", "TestController")

Create an action with return type of ViewResult that will return the overloaded ViewResult which takes in string parameter. That string is the name of your view.
Or you can use RedirectAction to redirect to a different controller's action. I think this is what you are after.

If you want to redirect to Account page together with the data. Below would be my suggestion.
public ActionResult PostToAccount() {
var accountModel = new AccountModel();
return RedirectToAction("Account", "Account", accountModel);
}
If you want ajax based where both Account view and Test view are rendered in a single page. Try the ajax approach
Login.cshtml
<div id="feed"></div>
Index.cshtml
View
<script>
function postData() {
$.ajax({
url: '/Test/PostToAccount'
data: {
someData: 'feed'
},
success: function(data) {
$("#feed").data(data.result);
}
});
}
</script>
<button onclick="postData"></button>
Controller
public class TestController : Controller {
public ActionResult PostToAccount(string someData) {
var accountModel = new AccountModel();
accountModel.Feed = feed;
return View("~/Views/Test/Index.cshtml", accountModel);
}
}

Related

action not found on alternate builds

I have a form like the following.
<form method="post" action="paste">
The page rendering the form and the action the form points to are both part of the same controller.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Paste()
{ // some field operations here.}
}
Now, in first build the form submission causes a 404 with a message The resource cannot be found. I edit the cshtml file and replace paste in the form tag with itself, build again and deploy and the form works fine. Why is it happening so and how can I correct the behaviour ?
It should work by adding the [HttpPost] attribute to your action.
[HttpPost]
public ActionResult Paste()
{ // some field operations here.}

Call another controller and use a different Layout for the called controller action MVC ASP.NET

Am new to MVC ASP.Net. I would like to call an action method from another controller and use a different layout page.
My Views/Shared folder has two layout pages: ~/Views/Shared/_Layout1.cshtml and ~/Views/Shared/_Layout2.cshtml. Below is my code:
//HomeController
public class HomeController : Controller
{
public ActionResult Index(string id)
{
if(String.IsNullOrEmpty(id))
{
//Call someMethod from UserController
//And when called, it should a different Layout page: ~/Views/Shared/_Layout2.cshtml
return View("someMethod");
}
else
{
return AboutPage(id); //uses ~/Views/Shared/_Layout1.cshtml
}
}
public ActionResult AboutPage(string id)
{
return View();
}
}
If you want to use different layout then you can use overloaded version of View method:
return View("view", "_Layout1");
If you want to redirect control flow to different controller/action then:
return RedirectToAction("action", "controller");

Partial view with #HTML.Action(...)

I have a strongly typed partial view that should show the name of an account that a user is logged into:
#model MyNamespace.Models.AccountNameViewModel
#if (Request.IsAuthenticated)
{
#Html.Action("AccountName", "AccountNameController", Model)
Logged in to #Model.AccountName
}
I have a controller:
public class AccountNameController : Controller
{
public ActionResult Index()
{
return View();
}
[ChildActionOnly]
public ActionResult AccountName(AccountNameViewModel model)
{
... Do somthing with the repository to populate the model
return PartialView(model);
}
}
What I want to do is add a shared partial view that displays the name of an account that a user is logged into. What I get is the following error:
The controller for path '/ParentViewPath/' was not found or does not implement IController.
Am I at least heading in the right direction?
You have to remove the controller part in your call
#Html.Action("AccountName", "AccountName", Model)
To render a partial view you can also call
#Html.Partial("AccountName", "AccountName", Model)

Retrieve data from partial view on post request via jQuery

I have a view that dynamically updates depending on user input - here's how it works:
View is rendered with initial data from controller populated with a partial view
When something is clicked, I use retrieve a partial view from an ActionResult from the controller and replace existing data with jQuery
I need a string from the controller for the main view, so I make another call to the controller and retrieve a string.
I want to know if there's a way to get the string I need with the partial view instead of making a separate controller call.
Initial Data:
<!-- This needs to change when the partial is replaced, but it's heavier html
and I don't want to include it in the partial to minimize server calls/data -->
<div class="Location"> </div>
<div class="myContainingDiv">
<!-- This content gets updated -->
#Html.Partial("_MyPartial");
</div>
Partial View:
<div class="something">Model.something</div>
Controller Method (Partial View):
[HttpGet]
public ActionResult _MyPartial(string param1)
{
MyModel model = new MyModel();
// This is dynamic and what I need to get in my main view from the partial view
model.something = "Hi";
return PartialView(model);
}
Controller Method (Return desired string):
public string GetHiString(string param1)
{
return "Hi";
}
JavaScript (Update partial view):
$.post('/Home/_MyPartial', { 'param1': 'Hi' }, function (result) {
$('.something').replaceWith(result);
getOtherThing('Hi');
});
JavaScript (getOtherThing):
$.post('/Home/_GetHiString', { 'param1': 'Hi' }, function (result) {
$('.Location').replaceWith(result);
});
OK, i think that's everything.
Basically I only want to hit the controller once per call. Including the div in the partial view is not an ideal option.
I hit the controller the second time from my main view to get data that can easily be created from an object within the first method and sent down to the partial view.
So, besides including <div class="Location"> in my partial view, is there a way to send the extra information I need to the partial view and retrieve it dynamically from my main view (via JavaScript). Or is there a way to return additional data when I call _MyPartial from my JavaScript?
This is really the last simplification I want to make and i'd really appreciate the help!
You could modify your partial view _MyPartial and it's model to include something hidden within it that you could extract using jQuery:
Partial View
<div class="something">Model.something
<input class="somethingElse" type="hidden" value="#(Model.somethingElse)" />
</div>
Controller Method (Partial View):
[HttpGet]
public ActionResult _MyPartial(string param1)
{
MyModel model = new MyModel();
// This is dynamic and what I need to get in my main view from the partial view
model.something = "Hi";
model.somethingElse = GetHiString(param1);
return PartialView(model);
}
JavaScript (Update partial view)
$.post('/Home/_MyPartial', { 'param1': 'Hi' }, function (result) {
$('.something').replaceWith(result);
$('.Location').html($('.somethingElse').val());
});

How do I pass an ID to the controller in ASP.NET MVC?

I have 4-5 partial view files (.ascx) like abc.ascx, cde.ascx, fgh.ascx.
I want to return different partial views based on the name of the view passed to url parameter like the following:
/someservice/abc will go to action someservice and will return abc.ascx partial view.
/someservice/cde will go to action someservice and will return cde.ascx partial view.
How can achieve this?
Try this... (untested, if it doesn't work let me know and I'll have a play with it)
In your Global.asax.cs, above the default route, map this route:
routes.MapRoute(
"SomeService",
"Home/SomeService/{view}",
new { controller = "Home", action="SomeService", view = "" }
);
In your controller:
public class HomeController : Controller
{
public ActionResult SomeService(string view)
{
return View(view);
}
}
Call it with Home/SomeService/abc etc...

Categories