Using Controller to get data into mvc grid - c#

I want to load mvc grid with data from controller:
Code:
GridView dumasGrid:
#model IEnumerable<BoneID.Dumas.Obroci>
#{
ViewBag.Title = "PopisObroka";
WebGrid grid = new WebGrid(Model, ajaxUpdateContainerId: "tblGrid");
}
<div>
#grid.GetHtml();
</div>
View page that load grid view page: dumasGridPlaner:
#using BoneID.Classes
#using BoneID.Net.Static
#model BoneID.Web.Models.ModelDefault
#{
var isIzoProd = Model.ParametriEx.Any(a => a.Type == CParametriEx.ParametriExType.IzoProd);
}
<div>
#Html.Partial("dumasGrid");
</div>
Main page that load page with grid: Dumas
<div id="tabs-1">
#Html.Partial("dumasGridPlaner",Model.Default)
</div>
My controller:
namespace BoneID.Web.Client.Controllers
{
public class DumasController : Controller
{
public ActionResult Index()
{
return View();
}
[ChildActionOnly]
public ActionResult PopisObroka()
{
Obroci obr = new Obroci();
var menu = obr.GetObroci();
return PartialView(menu);
}
}
}
Error that I get on page DumasGridPlaner:
System.InvalidOperationException: 'The model item passed into the dictionary is of type 'BoneID.Web.Models.ModelDefault', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[BoneID.Dumas.Obroci]'
What is the problem? What am I calling wrong?

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;
}

MVC 4 View reload with change in data

I have a simple controller and view:
I just want the Index.cshtml view page to be reloaded with new data.I have debugged the code thoroughly. Infact, clicking on the "ul" when the control goes to the Index(string value) method the model object is populated with new data and even in the cshtml page the Model is showing the new list in the debugger, but the view is NOT getting refreshed. I really don't know why.. Can anyone help me plz?
If I have gone wrong horribly somewhere please excuse my ignorance as I am new to MVC.
Thanks in advance...
Controller:
namespace MVCTestApp1.Controllers
{
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
ModelState.Clear();
List<string> ll = new List<string>();
ll.Add("qq");
ll.Add("aa");
ll.Add("zz");
return View(ll);
}
[HttpPost]
public ActionResult Index(string value)
{
ModelState.Clear();
List<string> ll = new List<string>();
ll.Add("kkk");
ll.Add("qq");
ll.Add("aa");
ll.Add("zz");
return View(ll);
}
}
}
View:
#model IEnumerable<string>
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<h2>Index</h2>
<ul id="bb">
#foreach (var i in Model)
{
<li>#Html.DisplayFor(ir=>i)</li>
}
</ul>
}
I suppose that you wrote some javascript code so that when the user clicks on a <li> element of the <ul> you are triggering an AJAX call to the [HttpPost] action sending the selected value to the server. The problem with your code might be that you probably forgot to update the DOM with the new contents in your success callback. So for this to work you could start by placing the <ul> contents in a partial view:
List.cshtml:
#model IEnumerable<string>
#foreach (var i in Model)
{
<li>#Html.DisplayFor(ir=>i)</li>
}
and then include this partial in the main view:
#model IEnumerable<string>
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<h2>Index</h2>
<ul id="bb">
#Html.Partial("_List", Model)
</ul>
}
OK, now in your POST action you could return the partial:
[HttpPost]
public ActionResult Index(string value)
{
List<string> ll = new List<string>();
ll.Add("kkk");
ll.Add("qq");
ll.Add("aa");
ll.Add("zz");
return PartialView("_List", ll);
}
and the final bit is the javascript code:
$(function() {
$('#bb').on('click', 'li', function() {
var value = $(this).html();
$.ajax({
url: $(this).closest('form').attr('action'),
type: 'POST',
data: { value: value },
success: function(partialView) {
$('#bb').html(partialView);
}
});
});
});

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

Load two controllers in the same view

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);
}

Categories

Resources