asp.net mvc user control problem
User Control
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%
using (MvcApplication1.Models.EgovtDataContext _model = new MvcApplication1.Models.EgovtDataContext())
{
%>
<% foreach(var md in MvcApplication1.Models.) { %>
<% if (md.ParentId == 0)
{ %>
<% } %>
<% } %>
<%} %>
FeatureRepository Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.Models
{
public class FeaturesRepository
{
EgovtDataContext db = new EgovtDataContext();
public IEnumerable<Feature> GetAllFeatures()
{
List<Feature> Features = new List<Feature>();
Feature feature = new Feature();
var AllParentFeatures = FeaturesByParentId(0);
foreach (Feature frParentCategory in AllParentFeatures)
{
feature.int_FeatureId = frParentCategory.int_FeatureId;开发者_运维百科
feature.vcr_FeaturesName = frParentCategory.vcr_FeaturesName;
feature.int_ParentId = frParentCategory.int_ParentId;
Features.Add(feature);
var AllChildFeaturesofthatParent = FeaturesByParentId(frParentCategory.int_FeatureId);
int AllChildFeaturesofthatParentCount = AllChildFeaturesofthatParent.Count();
foreach (Feature frChildCategory in AllChildFeaturesofthatParent)
{
feature.int_FeatureId = frParentCategory.int_FeatureId;
feature.vcr_FeaturesName = frParentCategory.vcr_FeaturesName;
feature.int_ParentId = frParentCategory.int_ParentId;
Features.Add(feature);
}
}
return Features;
}
}
}
1) is this rightly done public IEnumerable GetAllFeatures() in the method above?And the method correctly written? 2) I want to call the GetAllFeatures method in the control above ? how would i do that? 3) User Controller should be created in shared folder? What is shared folder for?
Create a controller action
public ActionResult All()
{
return View(new FeaturesRepository().GetAllFeatures());
}
And change your usercontrol declaration
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Feature>>" %>
<% foreach(var md in Model)
{ %>
<% if (md.ParentId == 0)
{ %>
//blabla
<% } %>
<% } %>
You need to create an instance of this repository class in your controller and using the instance call the method which return a IList of all the features and access that Ilist in your model.
The above method looks fine, though I don't know your business rules specifics. Just some code syntax changes would be nice (like Features with capital F, is wrong casing), etc.
With regards to the call, you can't just call the above method from a View or View User control. You have to populate the ViewData or Model with data from this method before you render the view. An alternative would be to use JavaScript, specifically JSON calls to request data from an action that returns JsonResult or ContentResult or something similar.
Controller actions should typical return ActionResult or the type inheriting from it (ContentResult, JsonResult, RedirectToActionResult etc.).
精彩评论