I have a Viewpage menu with controller Menucontroller. I have a partialView ViewItems which is strongly typed as object BagItem with contro ller BagItem.
I am trying to render the partial View from View page(Menu.aspx) and can't render partial View. Any help would be greatly appreciated.New to MVC. Here is the code
Menu.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MenuItem>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
OrderMenu
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
OrderMenu</h2>
<div>
<table>
<tr>
<td>
<% List<BagItem> sb = new List<BagItem>(); %>
<% Html.RenderPartial("../ShoppingBagItem/ViewItems", sb, (ViewDataDictionary)ViewData["BagItems"]);%>
</td>
</tr>
</table>
</div>
partialView
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<GuessCafe.Library.BagItem>>" %>
<body>
<div id="divLatestStocks">
<%foreach (var item in Model)
{ %>
<ul>
<li>
<%= item.ShoppingBagItemId %>
</li>
</ul>
<%}
%>
</div>
</body>
BagItemController
public ActionResult GetShoppingBagItems()
{
ViewData["BagItems"] = ObjectContext.BagItem.ToList();
return View(ViewData["BagItems"]);
}
I think what you want is simply this:
<% Html.RenderPartial("ViewItems", ViewData["BagItems"]); %>
This is assuming your partial view is named ViewItems.ascx.
You can remove the following line from your view:
<% List<BagItem> sb = new List<BagItem>(); %>
Update: your partial view should not contain <body>...</body> tags. These should either be on the master page.
public ActionResult GetShoppingBagItems()
{
ViewData["BagItems"] = ObjectContext.BagItem.ToList();
return View(ViewData["BagItems"]);
}
This is a bad practice at all. If you want pass Model to view why just use ViewData Dictionary ?
You can simply write :
public ActionResult GetShoppingBagItems()
{
var BagItems = ObjectContext.BagItem.ToList();
return View(BagItems);
}
Related
I have a view strongly-typed with the model VersaoUpload called index and this model has a member IEnumerable ArqUpload that contain two fields typed string.
The view index has a button to add dynamic field, when I click on this button, Code render a partial view strongly-typed ArqUpload called FileEditBox to add the field.
But I don't get the data of the dynamic fields.
View Index
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<UPDATE.ViewModels.VersaoUpload>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<h2>Index</h2>
<% using(Html.BeginForm()) { %>
<div id="editorRows">
<% foreach (var item in Model.Arqs)
Html.RenderPartial("FileEditRow", item);
%>
</div>
<%= Html.ActionLink("Add another...", "Add", null, new { id = "addItem" }) %>
<% } %>
</asp:Content>
View FileEditBox:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<UPDATE.ViewModels.ArqUpload>" %>
<%# Import Namespace="UPDATE.Helpers"%>
<div class="editorRow">
<% using(Html.BeginCollectionItem("files")) { %>
Arquivo: <%= Html.FileBoxFor(x => x.Arquivo) %>
Tipo:
<%=Html.RadioButtonFor(x => x.Tipo,"1")%> Sql
<%=Html.RadioButtonFor(x => x.Tipo,"2")%> Package
<%=Html.RadioButtonFor(x => x.Tipo,"3")%> Config
delete
<% } %>
</div>
The Controller:
public ViewResult Add()
{
return View("FileEditRow", new ArqUpload());
}
[HttpPost]
public ActionResult Index(VersaoUpload versao)
{
// To do: do whatever you want with the data
return View("Resultado",versao);
}
And this is the view Resultado to view the result:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<UPDATE.ViewModels.VersaoUpload>" %>
<% foreach (ArqUpload it in Model.Arqs)
{ %>
<div class="display-label">Tipo Arquvo</div>
<div class="display-field"><%: it.Tipo %></div>
<% } %>
But, the it.Tipo is null.
I have a strongly typed partial view which is giving me "Object reference not set to an instance of an object" error when I launch the master view. I know I am not passing in any parameters yet, but is there a way to handle this error?
Master View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Test Form
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="partial">
<% Html.RenderPartial("DisplayPartial"); %>
</div>
</asp:Content>
Partial View:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Student.Models.vwStudent>>" %>
<% foreach (var item in Model) {
if (item == null) continue; %>
<tr>
<td>
<%: item.Item1%>
</td>
<td>
<%: item.Item2%>
</td>
</tr>
<% } %>
</table>
You have to pass some Model to your partialView, because it need a instance of IEnumerable<Student.Models.vwStudent>
<% Html.RenderPartial("DisplayPartial", model); %>
Or, you can check in your partial view if the model is not null.
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Student.Models.vwStudent>>" %>
<% if (Model != null) {
foreach (var item in Model) {
if (item == null) continue; %>
<tr>
<td>
<%: item.Item1%>
</td>
<td>
<%: item.Item2%>
</td>
</tr>
<% }
} %>
</table>
If you need to render this partial view when you don't have a Model, you can certainly test that Model is not null before the foreach loop
if (Model != null)
foreach (...)
How i can do view for such code, if i have join? in asp.net mvc on c# language
public ActionResult Details(int id)
{
var routeDetails = (from rd in db.Route
join rdd in db.RouteDetail
on rd.RouteId equals rdd.RouteId
where rd.RouteId == id
select new
{
RouteId = rd.RouteId,
Name = rd.Name,
Station = rdd.Station,
TimeArrival = rdd.TimeArrival,
TimeDeparture = rdd.TimeDeparture
}).First();
return View(routeDetails);
}
I can do view for one table without join, but how it will be with join?
here is how i do it without join for edit action:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Main.Master" Inherits="System.Web.Mvc.ViewPage<TrainShedule.Models.Route>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Edit
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Edit</h2>
<% using (Html.BeginForm())
{%>
<%= Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<ul>
<li>Название маршрута:
<%= Html.TextBoxFor(m => m.Name) %>
<%= Html.ValidationMessageFor(m => m.Name)%>
</li>
</ul>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
<div>
<%= Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
You're creating an anonymous type for your routeDetails variable. If you want a strongly-typed view, you can define a new model class (RouteRouteDetail or similar) that contains the properties you want from both tables, and select instances of that type rather than selecting anonymous type instances using the new {} syntax.
I have a form with tabs. Subordinate to each tab is a partial view.
When the user submits to save changes, I want to call a method for that partial view, so for the partial view I put in <% using (Html.BeginForm(...) %>. But this gets ignored and clicking submit will call the method associated with the container view instead. Why is this, and how do I get this to work?
The View looks like;
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Employee.Master" Inherits="System.Web.Mvc.ViewPage<SHP.WebUI.Models.HolidayRequestViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
HolidayRequest
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="EmployeeContent" runat="server">
<% using (Html.BeginForm()) {%>
<%: Html.AntiForgeryToken() %>
<h2>Holiday Request</h2>
<p>You have <%: Html.DisplayFor(model => model.DaysAvailableThisYear) %> days left annual leave for this year
and <%: Html.DisplayFor(model => model.DaysAvailableNextYear) %> days left for next year.</p>
<p>If your request is approved and exceeds the number of days left, then those extra days will not be paid.</p>
<div id="tabs">
<ul>
<li>Approver</li>
<li>Single Date</li>
<li>Date Range</li>
</ul>
<div id="tabs-1">
<% Html.RenderPartial("GetApproverTab", Model); %>
</div>
<div id="tabs-2">
<% Html.RenderPartial("GetSingleDateTab", Model); %>
</div>
<div id="tabs-3">
<% Html.RenderPartial("GetDateRangeTab", Model); %>
</div>
</div>
<%: Html.HiddenFor(x => x.EmployeeId) %>
<% } %>
</asp:Content>
The partial view looks like;
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SHP.WebUI.Models.HolidayRequestViewModel>" %>
<% using (Html.BeginForm("GetSingleDateTab", "Employee", FormMethod.Post, new { id = "frmSingleDate" }))
{ %>
<p>Enter your day or part day of Annual Leave here.</p>
<table>
<tr>
<td align="right">Date:</td>
<td><%: Html.EditorFor(x => x.SingleDate) %></td>
</tr>
<tr>
<td align="right">Morning Only:</td>
<td><%: Html.CheckBoxFor(x => x.MorningOnlyFlag) %></td>
</tr>
<tr>
<td align="right">Afternoon Only:</td>
<td><%: Html.CheckBoxFor(x => x.MorningOnlyFlag) %></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save" /></td>
</tr>
</table>
<% } %>
and the controller looks like;
#region Employee Holiday Request
public ActionResult HolidayRequest()
{
return View(new HolidayRequestViewModel(Employee.GetLoggedInUser().EmployeeId));
}
[HttpPost] // This is the method that gets executed
public ActionResult HolidayRequest(HolidayRequestViewModel hrvm)
{
if (ModelState.IsValid)
{
hrvm.Update();
return View(new HolidayRequestViewModel(hrvm.EmployeeId));
}
return View(hrvm);
}
[HttpPost] // This is the method I want to get executed.
public ActionResult GetSingleDateTab(HolidayRequestViewModel hrvm)
{
if (ModelState.IsValid)
{
hrvm.Update();
return View(new HolidayRequestViewModel(hrvm.EmployeeId));
}
return View("GetSingleDateTab", hrvm);
}
#endregion
You can't have nester forms in html.
I discover an unbelievable solution. Just insert a <script> tag above the <form> tag.
<script type="text/javascript">
// don't remove <script> tag
</script>
<form ....
I'm creating a simple form to upload a file (which can be given a friendly name).
I've gone over this code time and time again, but always get a 404 when the form posts to /MyEntities/Add (this is a post-only URL on purpose).
Any thoughts would be much appreciated - I simply can't see what I've done wrong.
The controller:
public class MyEntitiesController : Controller
{
private DataFilesComparisonRepository repository = new DataFilesComparisonRepository();
public ActionResult Index()
{
List<MyEntitiesDataset> datasets = repository.GetMyEntitiesDatasets();
return View(datasets);
}
[HttpPost]
public ActionResult Add(HttpPostedFileBase postedFile, string friendlyName)
{
repository.AddMyEntities(friendlyName, postedFile.FileName, postedFile.InputStream);
return RedirectToAction("Index");
}
}
And the view:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<MyEntitiesDataset>>" %>
<%# Import Namespace="DataFilesComparison.Models" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
The Title
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% Html.BeginForm("Add", "MyEntities", FormMethod.Post, new { enctype = "multipart/form-data" }); %>
<p>
<input type="file" name="postedFile" />
<label for="friendlyName">Friendly Name:</label>
<%= Html.TextBox("friendlyName") %>
<input type="submit" value="Add" />
</p>
<% Html.EndForm(); %>
<% if (Model == null || Model.Count == 0) { %>
<p>No datasets found.</p>
<% } else { %>
<ul>
<% foreach (MyEntitiesDataset dataset in Model) { %>
<li>
<%= dataset.Name %>
[<%= Html.ActionLink("X", "Delete", new { ID = dataset.ID })%>]
</li>
<% } %>
</ul>
<% } %>
</asp:Content>
The model you are passing into the view is not the same of the same type that you are posting back into the Add() method, which may be confusing the default routing settings. Although I see you have been explicit about which method to call, I have had problems like this before. Maybe try creating a ViewModel with the properties you need for the GET and POST, then using them in both the View and the Controller methods. Like this:
Model
public MyViewModel
{
public List<MyEntitiesDataset> Datasets {get; set;}
public HttpPostedFileBase PostedFile {get; set;}
public string FriendlyName {get; set;}
}
Controller Methods
public ActionResult Index()
{
MyViewModel model = new MyViewModel();
model.Datasets = repository.GetMyEntitiesDatasets();
return View(datasets);
}
[HttpPost]
public ActionResult Add(MyViewModel model)
{
repository.AddMyEntities(model.FriendlyName, Model.PostedFile.FileName, Model.postedFile.InputStream);
return RedirectToAction("Index", model);
}
View
%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyViewModel>" %>
<%# Import Namespace="DataFilesComparison.Models" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
The Title
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% Html.BeginForm("Add", "MyEntities", FormMethod.Post, new { enctype = "multipart/form-data" }); %>
<p>
<input type="file" name="postedFile" />
<label for="Model.FriendlyName">Friendly Name:</label>
<%= Html.TextBoxFor(m => m.FriendlyName) %>
<input type="submit" value="Add" />
</p>
<% Html.EndForm(); %>
<% if (Model.Datasets == null || Model.Datasets.Count == 0) { %>
<p>No datasets found.</p>
<% } else { %>
<ul>
<% foreach (var dataset in Model.Datasets) { %>
<li>
<%= dataset.Name %>
[<%= Html.ActionLink("X", "Delete", new { ID = dataset.ID })%>]
</li>
<% } %>
</ul>
<% } %>
</asp:Content>
You might have to play around with the file uploader (not sure if there is an Html.FileFor, but hopefully you get the idea!
Good luck.