当前位置: 移动技术网 > IT编程>开发语言>.net > MVC4制作网站教程第四章 添加栏目4.1

MVC4制作网站教程第四章 添加栏目4.1

2017年12月12日  | 移动技术网IT编程  | 我要评论
好几天没时间写了。今天有写时间在学一点。 今天状态也不是很好,晕晕沉沉的写吧。 序 一、用户 二、用户组 三、栏目 3.1添加栏目 首先添加【category

好几天没时间写了。今天有写时间在学一点。
今天状态也不是很好,晕晕沉沉的写吧。

一、用户
二、用户组
三、栏目
3.1添加栏目
首先添加【categorycontroller】控制器, 

那么我想我的视图里,首先显示的应该是栏目类型,这里应该是一个下拉框,用户可以选择“一般栏目”,“单页栏目”,“外部链接”。那么首先应该在【categorycontroller】添加一个属性,用来返回栏目类型列表。 

#region attribute
 public list<selectlistitem> typeselectlist
 {
  get
  {
  list<selectlistitem> _items = new list<selectlistitem>();
  _items.add(new selectlistitem { text = categorytype.一般栏目.tostring(), value = ((int)categorytype.一般栏目).tostring() });
  _items.add(new selectlistitem { text = categorytype.单页栏目.tostring(), value = ((int)categorytype.单页栏目).tostring() });
  _items.add(new selectlistitem { text = categorytype.外部链接.tostring(), value = ((int)categorytype.外部链接).tostring() });
  return _items;
  }
 }
 #endregion

其次,用户应该可以选择内容模型,内容模型是什么? 

内容模型就是这个栏目下可以添加内容的模型名称?这个模型名称对应的就是models中间的模型类。为了更好的表述在系统中添加模块“module ”的概念。模块用来指系统中用来实现相应功能的块,想新闻模块,文章模块,留言模块,图片模块,产品模块,服务模块等等,每个模块对应相应的模型和控制器,用来实现设想中的功能。系统中预置的模块用户应该可以设置启用还是关闭。 

第一应该添加内容模型类

using system.componentmodel.dataannotations;

namespace ninesky.models
{
 /// <summary>
 /// 内容模块
 /// </summary>
 public class module
 {
 [key]
 public int moduleid { get; set; }
 /// <summary>
 /// 模块名称
 /// </summary>
 [required(errormessage="×")]
 [display(name="模块名称")]
 public string name { get; set; }
 /// <summary>
 /// 模块模型
 /// </summary>
 [required(errormessage = "×")]
 [display(name = "模块模型")]
 public string model { get; set; }
 /// <summary>
 /// 启用模块
 /// </summary>
 [required(errormessage = "×")]
 [display(name = "启用模块")]
 public bool enable { get; set; }
 /// <summary>
 /// 说明
 /// </summary>
 [required(errormessage = "×")]
 [display(name = "说明")]
 public string description { get; set; }

 }
}

既然有模块类,就应该有模块类的数据处理类modulerepository,这块功能暂时留在后面来写,先最简单的实现list(bool enable)函数让其能显示模块列表。 

using ninesky.models;
using system.collections.generic;
using system.linq;

namespace ninesky.repository
{
 public class modulerepository
 {
 public iqueryable<module> list(bool enable)
 {
  list<module> _module = new list<module>();
  _module.add(new module { name = "新闻模块", model = "news", enable = true, description = "新闻模块" });
  _module.add(new module { name = "文章模块", model = "article", enable = true, description = "文章模块" });
  return _module.asqueryable();
 }
 }
}

简单吧。模块功能以后再写吧,先为了添加栏目显示两个固定的模块,
 那么后续我们要在控制器中添加[manageadd]action 

[adminauthorize]
 public actionresult manageadd()
 {
  modulerepository _modulersy = new modulerepository();
  var _modules = _modulersy.list(true);
  list<selectlistitem> _slimodule = new list<selectlistitem>(_modules.count());
  foreach (module _module in _modules)
  {
  _slimodule.add(new selectlistitem { text = _module.name, value = _module.model });
  }
  viewdata.add("model", _slimodule);
  viewdata.add("type", typeselectlist);
  return view();
 }

然后添加添加数据处理函数

[adminauthorize]
 [httppost]
 public actionresult manageadd(category category)
 {
  categoryrsy = new categoryrepository();
  if (categoryrsy.add(category))
  {
  notice _n = new notice { title = "添加栏目成功", details = "您已经成功添加[" + category.name + "]栏目!", dwelltime = 5, navigationname = "栏目列表", navigationurl = url.action("managelist", "cayegory") };
  return redirecttoaction("managenotice", "prompt", _n);
  }
  else
  {
  error _e = new error { title = "添加栏目失败", details = "在添加栏目时,未能保存到数据库", cause = "系统错误", solution = server.urlencode("<li>返回<a href='" + url.action("manageadd", "cayegory") + "'>添加栏目</a>页面,输入正确的信息后重新操作</li><li>联系网站管理员</li>") };
  return redirecttoaction("manageerror", "prompt", _e);
  }
 }

现在开始做视图部分了。
在[manageadd]action上点右键添加视图, 

@model ninesky.models.category

@{
 viewbag.title = "manageadd";
 layout = "~/views/layout/_manage.cshtml";
}

<div class="left">
 <div class="top"></div>
 左侧列表
</div>
<div class="split"></div>
<div class="workspace">
 <div class="inside">
 <div class="notebar">
  <img alt="" src="~/skins/default/manage/images/category.gif" />添加栏目
 </div>

 @using (html.beginform())
 {
  @html.validationsummary(true)

  <fieldset>
  <legend>栏目</legend>
  <ul>
   <li>
   <div class="editor-label">
    @html.labelfor(model => model.type)
   </div>
   <div class="editor-field">
    @html.dropdownlist("type")
    @html.validationmessagefor(model => model.type)
    @html.displaydescriptionfor(model => model.type)
   </div>
   </li>
   <li>
   <div class="editor-label">
    @html.labelfor(model => model.name)
   </div>
   <div class="editor-field">
    @html.editorfor(model => model.name)
    @html.validationmessagefor(model => model.name)
    @html.displaydescriptionfor(model => model.name)
   </div>
   </li>
   <li>
   <div class="editor-label">
    @html.labelfor(model => model.parentid)
   </div>
   <div class="editor-field">
    @html.editorfor(model => model.parentid)
    @html.validationmessagefor(model => model.parentid)
    @html.displaydescriptionfor(model => model.parentid)
   </div>
   </li>
   <li id="li_model">
   <div class="editor-label">
    @html.labelfor(model => model.model)
   </div>
   <div class="editor-field">
    @html.dropdownlist("model")
    @html.validationmessagefor(model => model.model)
    @html.displaydescriptionfor(model => model.model)
   </div>
   </li>
   <li id="li_categoryview">
   <div class="editor-label">
    @html.labelfor(model => model.categoryview)
   </div>
   <div class="editor-field">
    @html.editorfor(model => model.categoryview)
    @html.validationmessagefor(model => model.categoryview)
    @html.displaydescriptionfor(model => model.categoryview)
   </div>
   </li>
   <li id="li_contentview">
   <div class="editor-label">
    @html.labelfor(model => model.contentview)
   </div>
   <div class="editor-field">
    @html.editorfor(model => model.contentview)
    @html.validationmessagefor(model => model.contentview)
    @html.displaydescriptionfor(model => model.contentview)
   </div>
   </li>
   <li id="li_nav">
   <div class="editor-label">
    @html.labelfor(model => model.navigation)
   </div>
   <div class="editor-field">
    @html.editorfor(model => model.navigation)
    @html.validationmessagefor(model => model.navigation)
    @html.displaydescriptionfor(model => model.navigation)
   </div>
   </li>
   <li>
   <div class="editor-label">
    @html.labelfor(model => model.order)
   </div>
   <div class="editor-field">
    @html.editorfor(model => model.order)
    @html.validationmessagefor(model => model.order)
    @html.displaydescriptionfor(model => model.order)
   </div>
   </li>
   <li>
   <div class="editor-label">
   </div>
   <div class="editor-field">
    <input type="submit" value="添加" />
   </div>
   </li>
  </ul>
  </fieldset>
 }
 </div>
</div>
<div class="clear"></div>
@section scripts {
 @scripts.render("~/bundles/jqueryval")
}

这里给一些<li>添加id属性,实现用户在显示不同的栏目类型的时候显示不同的项目。
 在manageadd.cshtml底部添加脚本 

<script type="text/javascript">
 details();
 $("#type").change(function () {
 details();
 });
 function details() {
 var v = $("#type").val();
 if (v == "0") {
  $("#li_model").show();
  $("#li_categoryview").show();
  $("#li_contentview").show();
  $("#li_nav").hide();
 }
 else if (v == "1") {
  $("#li_model").hide();
  $("#li_categoryview").show();
  $("#li_contentview").hide();
  $("#li_nav").hide();
 }
 else if (v == "2") {
  $("#li_model").hide();
  $("#li_categoryview").hide();
  $("#li_contentview").hide();
  $("#li_nav").show();
 }
 }
</script>

从浏览器中看一下。父栏目这里还有些问题,设想中这里应该是一个下拉框,用户可以选择已存在栏目类型为一般栏目的栏目做父栏目。这里需要下拉树形列表,设想中应该是这个样子,是一个下拉列表和属性列表框的组合框。

html中没有这种类型的控件,mcv4 中带的jquery ui是一个比较好的库,本身包含一定的控件,并且可以自己扩展,但是他缺少一些像,数据表(datagirdview),树形控件(tree),树形组合控件(combotree)等,且jqueryui的式样也不太好变换,决定丢弃jqueryui,而是用easyui(相对jqueryui功能更全面,更容易控制式样),在“引用”上点右键选择管理nuget程序包 

在已安装的包->全部,选择jquery ui点击卸载。 

http://www.jeasyui.com/选在最新版本,在项目的/scripts文件夹中新建easyui文件夹,将easyui中的一下文件夹复制到该文件夹。

 

打开app_start\bundleconfig.cs,删除jqueryui相关项,添加

 bundles.add(new scriptbundle("~/bundles/easyui").include( 
   "~/scripts/easyui/easyloader.js"));
 
bundles.add(new stylebundle("~/easyui/icon").include("~/scripts/easyui/themes/icon.css"));

两项,使该文档看起来如下: 

using system.web;
using system.web.optimization;

namespace ninesky
{
 public class bundleconfig
 {
 // 有关 bundling 的详细信息,请访问 http://go.microsoft.com/fwlink/?linkid=254725
 public static void registerbundles(bundlecollection bundles)
 {
  bundles.add(new scriptbundle("~/bundles/jquery").include(
   "~/scripts/jquery-{version}.js"));

  bundles.add(new scriptbundle("~/bundles/easyui").include(
   "~/scripts/easyui/easyloader.js"));

  bundles.add(new scriptbundle("~/bundles/jqueryval").include(
   "~/scripts/jquery.unobtrusive*",
   "~/scripts/jquery.validate*"));

  // 使用 modernizr 的开发版本进行开发和了解信息。然后,当你做好
  // 生产准备时,请使用 http://modernizr.com 上的生成工具来仅选择所需的测试。
  bundles.add(new scriptbundle("~/bundles/modernizr").include(
   "~/scripts/modernizr-*"));

  bundles.add(new stylebundle("~/skins/css").include("~/skins/default/style.css"));
  bundles.add(new stylebundle("~/skins/usercss").include("~/skins/default/user.css"));
  bundles.add(new stylebundle("~/skins/managecss").include("~/skins/default/manage/style.css"));
  bundles.add(new stylebundle("~/easyui/icon").include("~/scripts/easyui/themes/icon.css"));
 }
 }
}

这里会用到easyui的combotree。
 查阅了官方文档,数据格式为
tree data format 
every node can contains following properties:
 •id: node id, which is important to load remote data
 •text: node text to show
 •state: node state, 'open' or 'closed', default is 'open'. when set to 'closed', the node have children nodes and will load them from remote site
 •checked: indicate whether the node is checked selected.
 •attributes: custom attributes can be added to a node
 •children: an array nodes defines some children nodes 

那么在models文件夹里新家ui文件夹,该文件夹用来控件数据相关的模型,添加tree类 

using system;
using system.collections.generic;
using system.linq;
using system.web;

namespace ninesky.models.ui
{
 /// <summary>
 /// 树形控件数据
 /// </summary>
 public class tree
 {
 /// <summary>
 /// id
 /// </summary>
 public int id { get; set; }
 /// <summary>
 /// 文本
 /// </summary>
 public string text { get; set; }
 /// <summary>
 /// 节点状态:'open'或'closed',默认'open'。
 /// </summary>
 public string state { get; set; }
 /// <summary>
 /// 图标
 /// </summary>
 public string iconcls { get; set; }
 /// <summary>
 /// 子节点
 /// </summary>
 public list<tree> children { get; set; }
 }
}

打开~/scripts/easyui/themes/icon.css文件 

在底部添加代码 

.icon-general { 
 background: url('icons/ns_general.png') no-repeat !important; 
}

切记一定记得加!important来调整css的优先级。easyui会将icon-general这个类添加在列表项的最后,如果不加这句'icons/ns_general.png'图标将不会显示。 

选择一个16*16的图表命名为ns_general.png,并复制到一下文件夹 

这里要用递归的方式调取一般栏目的树形结构:打开categoryrepository.cs。在底部添加两个函数 

/// <summary>
 /// 栏目列表
 /// </summary>
 /// <param name="model">模型名称</param>
 /// <returns></returns>
 public iqueryable<category> list(string model)
 {
  return dbcontext.categorys.where(c => c.model == model).orderby(c => c.order);
 }
 /// <summary>
 /// 普通栏目树形类表
 /// </summary>
 /// <returns></returns>
 public list<tree> treegeneral()
 {
  var _root = children(0, 0).select(c => new tree { id = c.categoryid, text = c.name, iconcls = "icon-general" }).tolist();
  if (_root != null)
  {
  for (int i = 0; i < _root.count(); i++)
  {
   _root[i] = recursiontreegeneral(_root[i]);
  }
  }
  return _root;
 }
 /// <summary>
 /// 普通栏目树形类表递归函数
 /// </summary>
 /// <param name="tree"></param>
 /// <returns></returns>
 private tree recursiontreegeneral(tree tree)
 {
  var _children = children(tree.id, 0).select(c => new tree { id = c.categoryid, text = c.name, iconcls="icon-general" }).tolist();
  if (_children != null)
  {
  
  for (int i = 0; i < _children.count(); i++)
  {
   _children[i] = recursiontreegeneral(_children[i]);
  }
  tree.children = _children;
  }
  return tree;
 }

打开categorycontroller,添加一个 [jsontreeparent()]  返回可以做父栏目的栏目树列表。

#region json
 [adminauthorize]
 public jsonresult jsontreeparent()
 {
  categoryrsy =new categoryrepository();
  var _children = categoryrsy.treegeneral();
  if (_children == null) _children = new list<tree>();
  _children.insert(0, new tree { id = 0, text = "无",iconcls="icon-general" });
  return json(_children);
 }
 #endregion

打开manageadd.cshtml,将@html.editorfor(model => model.parentid)改为<input id="parentid" type="text" class="easyui-combotree" data-options="url:'@url.action("jsontreeparent", "category")'" value="0" /> . 

在@section scripts中减价easyui的脚本和css引用 

@section scripts {
 @styles.render("~/easyui/icon")
 @scripts.render("~/bundles/easyui")
 @scripts.render("~/bundles/jqueryval")
} 


ok,打开浏览器测试一下 

可以正常添加栏目。 

今天发现一个问题无论父栏目宣布选什么,提交的parentid为0,上面“打开manageadd.cshtml,将@html.editorfor(model => model.parentid)改为<input id="parentid" type="text" class="easyui-combotree" data-options="url:'@url.action("jsontreeparent", "category")'" value="0" /> .” 这里有问题,应改为:@html.textbox("parentid",0,new {@class ="easyui-combotree",data_options="url:'"+url.action("jsontreeparent", "category")+"'" })。 

修改后正常了,但是使用easyui combotree后,父栏目客户端验证无效了,这个是什么原因,如何解决,知道的朋友不吝赐教!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网