Load two controllers in the same view - c#

I'm developing an mvc 4 application and I'm just about done. I have two controllers are there.
public ActionResult Index()
{
return View(new Resources());
}
public ActionResult ResourceDetails(int id = 1)
{
ResourceItems re = new Resources().GetResDetails(id);
return View(re);
}
ResourceDetails is a partial viewpage .it contains
#model ....Models.ResourceItems
<div>
#Html.Raw(#Model.Res_Details)
</div>
and index page contains
#model IEnumerable<.....Models.ResourceItems>
<ul id="res">
#foreach(var Item in Model)
{
<a href="~/Resources/ResourceDetails/#Item.Id" ><li>#Item.Res_NA</li></a>
}
</ul>
<div id="rescontent">
</div>
I want load the partial page in to the div "rescontent" based on Id. Defaultly Id is 1. how it possible

You could use AJAX:
#model IEnumerable<Puthencruz.Rotary.Club.Models.ResourceItems>
<ul id="res">
#foreach(var item in Model)
{
<li>
#Html.ActionLink(
item.Res_NA,
"ResourceDetails",
"Resources",
new { id = item.Id },
new { #class = "detail" }
)
</li>
}
</ul>
<div id="rescontent">
</div>
and then in a separate javascript file you could use jQuery to subscribe to the .click event of the anchors and send an AJAX request to the Details controller action sending the current item id and then render the results in the #rescontent div:
$(function() {
$('.detail').click(function() {
$('#rescontent').load(this.href);
return false;
});
});
Also from your controller action make sure you are returning a partial view:
public ActionResult ResourceDetails(int id = 1)
{
ResourceItems re = new Resources().GetResDetails(id);
return PartialView(re);
}

Related

How do i pass multiple actionresults from home controller to index.cshtml view

This is my controller code. The first method is to get 5 post to display in the homepage.
The second method is to display recent post in the sidebar.
How do I link it to display in the View which already shows the posts for the Index action?
Controller:
namespace ThelmaBlog.Controllers
{
public class HomeController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public ActionResult Index()
{
var posts = db.Posts.Include(p => p.Author).OrderByDescending(p => p.Date).Take(3);
return View(posts.ToList());
}
public ActionResult Sidebar()
{
var PostsTop5 = db.Posts.Include(path => path.Author).OrderByDescending(p => p.Date).Take(3);
return View(PostsTop5.ToList());
}
}
}
View:
#{
ViewBag.Title = "Home Page";
}
#model List<ThelmaBlog.Models.Post>
#foreach (var post in Model)
{
<div class="row">
<div class="post col-md-6">
<h2 class="title">#post.Title</h2>
<div class="about">
Posted on <i>#post.Date</i>
#if (post.Author != null)
{
#:by <i>#(post.Author.FullName + " (" + post.Author.UserName + ")")</i>
}
</div>
<div>
#Html.Raw(HttpUtility.HtmlDecode(post.Body))
</div>
</div>
</div>
}
#section Sidebar{
}
Change your Sidebar action so it returns a partial view:
public ActionResult Sidebar()
{
var PostsTop5 = db.Posts.Include(path => path.Author).OrderByDescending(p => p.Date).Take(3);
return PartialView("_Posts", PostsTop5.ToList());
}
Then, create a partial view, called _Posts.cshtml, with the following code:
#model List<ThelmaBlog.Models.Post>
#foreach (var post in Model)
{
<div class="row">
<div class="post col-md-6">
<h2 class="title">#post.Title</h2>
<div class="about">
Posted on <i>#post.Date</i>
#if (post.Author != null)
{
#:by <i>#(post.Author.FullName + " (" + post.Author.UserName + ")")</i>
}
</div>
<div>
#Html.Raw(HttpUtility.HtmlDecode(post.Body))
</div>
</div>
</div>
}
And, finally, change your Index view to this:
#model List<ThelmaBlog.Models.Post>
#{
ViewBag.Title = "Home Page";
}
#Html.Partial("_Posts", Model)
#section Sidebar{
#Html.Action("Sidebar", "Home")
}
By the way, neither of your actions return what you have described in your post. They both return exactly the same thing, which is the top 3 posts (not top 5).
add your sidebar content to new partialview and then render this partial view in index
#Html.Action("sidebar") // in your index page

Render whole page with PartialView (and data) on page load

Currently we have a page where you select some parameters and click on a button to load data and display it in a grid, but there is no functionality to display the data on page load (via url parameters) yet. I've added the necessary routing configurations and Action, but I'm having troubles to render the page, it only displays the PartialView without styles.
How can I get the whole page to render and not just the PartialView?
Below is my simplyfied code for the View and Controller.
Views/Planing/Index.cshtml
#model PlaningTool.Web.Models.PlaningViewModel
<div class="row">
<div>
#using (Ajax.BeginForm("GetDataRows",
"Planing",
new AjaxOptions
{
HttpMethod = "Get",
UpdateTargetId = "gridPlaceholder",
LoadingElementId = "loadingIndicator"
}))
{
<!-- some comboboxes to select project and year -->
<input type="submit" value="Load data" />
}
</div>
</div>
<div id="gridPlaceholder">
<div id="loadingIndicator" style="display: none;">
<img src="~/Content/images/loading-image.gif" />
</div>
</div>
Controllers/PlaningController.cs
public partial class PlaningController : Controller
{
public virtual ActionResult Index()
{
return View();
}
public virtual ActionResult Plan(long projectID, int year)
{
var viewModel = new PlaningViewModel
{
ProjectID = projectID,
Year = year
};
// return GetDataRows(viewModel);
return RedirectToAction("GetDataRows", viewModel);
}
[RestoreModelStateFromTempData(typeof(PartialViewResult))]
public virtual PartialViewResult GetDataRows(PlaningViewModel viewModel)
{
// Load data from database with viewModel.ProjectID
// and viewModel.Year as parameters
[...]
var vm = new PlaningViewModel
{
// Set ViewModel for loaded data
[...]
};
return PartialView("Shared/_PlaningViewModelRows", vm);
}
[...]
}
I finally found a solution. I'm pretty sure it's not the best way to do this but it works.
If the Model is already set I render the PartialView.
<div id="gridPlaceholder">
#{
if (Model != null)
{
Html.RenderPartial("Shared/_PDataViewModelRows", Model);
}
}
<div id="loadingIndicator" style="display: none;">
<img src="~/Content/kendo/Bootstrap/loading-image.gif"/>
</div>
</div>
And in my Controller I've changed to this, so my ViewModel gets loaded independently and I simply return the same view as I would for Index with the new ViewModel.
public virtual ActionResult Plan(long projectID, int year)
{
var viewModel = new PlaningViewModel
{
ProjectID = projectID,
Year = year
};
return View("Index", LoadViewModel(viewModel));
}
public PlaningViewModel LoadViewModel(PlaningViewModel viewModel)
{
// Load data from database with viewModel.ProjectID
// and viewModel.Year as parameters
[...]
var vm = new PlaningViewModel
{
// Set ViewModel for loaded data
[...]
};
return vm;
}

Counting how many times a button was clicked

I am wondering how can I count the number of times a button in my view was clicked using sessions and not using jQuery, just asp.net.
Here is my action method (empty) :
public ActionResult ClickCounter()
{
return View();
}
and my view :
#{
ViewBag.Title = "ClickCounter";
}
<h2>ClickCounter</h2>
#using (#Html.BeginForm())
{
<!-- form content here -->
#Session["num"] = 0;
<form method="post">
<fieldset>
<legend>Button clicks counter</legend>
<div>
<label for="Clciks">Clicks:</label>
<h2>#Session["num"]</h2>
</div>
<div>
<label> </label>
<input type="submit" value="Click!" class="submit" />
</div>
</fieldset>
</form>
}
Excuse me for the lame questions, but I am a complete novice and trying to understand how this stuff work. I tried googleing.
I just want to display the click count in the h2 in my view using sessions for the purpose.
Any tips will be appreciated.
If it is for simply increasing the clicked count on form submit, You can update your http post action method to read the session value if exist and increase and set it back. If not exist, initialize it.
const string sessionVariableName = "num";
public ActionResult ClickCounter()
{
if (Session[sessionVariableName] == null)
{
Session[sessionVariableName] = 0;
}
return View();
}
[HttpPost]
public ActionResult ClickCounter(string dummyParam)
{
if (Session[sessionVariableName] == null) // should not happen!
{
Session[sessionVariableName] = 0;
}
else
{
var n = (int)Session[sessionVariableName];
n++;
Session[sessionVariableName] = n;
}
return View();
}
Make sure that you are doing a GET form method on submit.
You also need to remove the (re) initialization in the view this line #Session["num"] = 0; as we are doing that in the action method. Also you should not have nested forms as it is invalid. Html.BeginForm helper will render the markup for the form tag. So remove the inner form tag you have.
You have tagged this question as asp.net-mvc, why not take advantage of the framework?
Model
class MyModel
{
public int ClickCount { get; set; }
}
View
#model MyModel
#{
ViewBag.Title = "ClickCounter";
}
<h2>#ViewBag.Title</h2>
<form method="post">
<!-- hidden input of the current click count -->
#Html.HiddenFor(m => m.ClickCount)
<fieldset>
<legend>Button clicks counter</legend>
<div>
#Html.LabelFor(m => m.ClickCount)
<h2>#Model.ClickCount</h2>
</div>
<div>
<button type="submit">Submit!</button>
</div>
</fieldset>
</form>
Controller
const string clickCountSessionKey = "clickCount";
[HttpGet]
public ActionResult ClickCounter()
{
// initialize the model
var model = new MyModel() { ClickCount = 0 };
var previousClickCount = Session[clickCountSessionKey];
if (previousClickCount != null)
{
model.ClickCount = (int)previousClickCount;
}
return View(model);
}
[HttpPost]
public ActionResult ClickCounter(MyModel model)
{
// increment the click count of the model
model.ClickCount++;
// track the click count in the session
Session[clickCountSessionKey] = model.ClickCount;
return View(model);
}

MVC 4 partial view causes page to become unresponsive on submit

Situation: In my C#/MVC 4 solution I am employing a view with a partial view within. The view is a form with a submit button. The partial view is with a div that is hidden, but can be displayed if the checkbox is selected.
Issue: If the partial view is hidden, the submit works normally. If the partial view is not hidden the submit causes the page to become unresponsive, if one waits the 3 plus minutes or so the submit eventually works as expected.
The code is below. Thank you in advance for your consideration. I am a novice developer, therefore all comments, suggestions and critiques are welcome.
Code:
Model
namespace MyModels
{
public class MainModel
{
public SelectListItem Things { get; set;}
public IEnumerable<OtherModel> MoreThings { get; set;}
}
}
View
//named MyView
#model MyModels.MainModel
#using MyModels
#if (Model != null){
using (Html.BeginForm("MyViewName", "MyControllerName", FormMethod.Post, new { id = "view-form" }))
{
#Html.LabelFor(model => model.things)
#Html.DropDownList("", (Selectist)ViewBag.things)
#Html.ValidationMessageFor(model => model.field1)
#Html.CheckBoxWithLabel("aNameAttribute", Model.valueAttribute.ToString(), "anIdAttribute", Model.valueAtttribue ==1, "aLabel", "a_Toggle_Class")
<div class="treeview" style="display: none;">
<fieldset>
<legend>Title</legend>
//view causing issues replaces the div below
<div id="replacedDiv"></div>
</fieldset>
</div>
<p>
<input type="submit" value="Submit" />
</p>
}
}
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: "/MyController/MyPartialView",
contentType: "application/html; charset=utf-8",
cache: "false",
type: "GET",
datatype: "html"
})
.success(function (result) {
$('#replacedDiv").html(result);
})
});
</script>
Partial View
//named _MyPartialView
#model MyModels.MainModel
#using MyModels
#foreach (var moreThings in ViewBag.moreThings)
{
<div id="replacedDiv">
<label>
<input type="checkbox" id=#moreThings.id value=#moreThings.name />#moreThings.name </label>
</div>
}
Controller
namespace Main.Controllers
{
public class MyController
{
[HttpGet]
public ActionResult Index(MainModel model)
{
return View(model);
}
public ActionResult MyView()
{
var model = new MainModel();
return View(model);
}
public ActionResult MyPartialView(MainModel model)
{
<OtherModel> moreThings = BLotherModel.GetMoreThings();
ViewBag.moreThings = moreThings;
return PartialView("_MyPartialView", promotion);
}
[HttpPost]
public ActionResult MyView(FormCollection collection)
{
MainModel model = new MainModel();
return SaveModel(model);
}
}
}
In your ajax you are using:
$('#replacedDiv").html(result);
But your partial view contains <div id="replacedDiv"> that are generated in a loop
replace your partial view code with :
#foreach (var moreThings in ViewBag.moreThings)
{
<label>#moreThings.name </label>
<input type="checkbox" id=#moreThings.id value=#moreThings.name />
}
and it should be OK

Not able to run another function for another button inside same view

I have got the two buttons in the same view one is working with the data to show in a label in another view and I have written the function for the button2 (adding another value), when I click on the button2 its not showing the data in view ..... rather it's giving error like this ... http:404 Resource not found error
and this is the view
#model MvcSampleApplication.Models.products
#{
ViewBag.Title = "Valuesadd";
}
<h2>Valuesadd</h2>
#using (Html.BeginForm("SubmitValue","EnterValue",FormMethod.Post))
{
<div>
<fieldset>
<legend>Enter Textbox Value</legend>
<div class ="editor-label">
#Html.LabelFor(m => m.EnteredValue)
</div>
<div class="editor-field">
#Html.TextBoxFor(m=>m.EnteredValue)
</div>
<p>
<input type="submit" value="Submit1" />
</p>
</fieldset>
</div>
}
#using (Html.BeginForm("SubmitValue2","EnterValue",FormMethod.Post))
{
<p>
<input type="submit" value="Submit2" />
</p>
}
and this is the controller for
namespace MvcSampleApplication.Controllers
{
public class EnterValueController : Controller
{
[HttpPost]
public ActionResult SubmitValue(MvcSampleApplication.Models.products model)
{
TempData["logindata"] = model.EnteredValue;
return RedirectToAction("submittedvalues" , "SubmitValue2");
// how can we redirect to another view when the button is clicked in one view
}
public ActionResult submittedvalues()
{
var model = new MvcSampleApplication.Models.category();
string data = TempData["logindata"] != null ? TempData["logindata"].ToString() : "";
model.lablvalue = data;
return View(model);
}
// action for second button click
public ActionResult submittedvalues2()
{
var model = new MvcSampleApplication.Models.category();
string data = TempData["logindata"] != null ? TempData["logindata"].ToString() : "";
model.lablvalue = "HIIII"+data;
return View(model);
}
}
}
would you pls suggest any idea ..
Many thanks...
Your form action and action in the controller are not named the same. Also you don't have a HttpPostfor it
#using (Html.BeginForm("SubmitValue2","EnterValue",FormMethod.Post))
{
}
//add this
[HttpPost]
public ActionResult submittedvalues2()
{
var model = SOMETHING;
return View("submittedvalues", model);
}
or
[HttpPost]
public ActionResult submittedvalues2()
{
//Do your post actions and redirect to action
return RedirectToAction("submittedvalues");
}
SubmitValue2 in the form should be submittedvalues2, and add a HttpPost attribute on it

Categories

Resources