Is it possible Single Controller for Entire MVC Application to Route Views Or can we Rename Controller Name at Run-time to Route Views?..
我尝试了以下代码以使路由视图正常运行。 控制器:-
public class HomeController : Controller
{
public ActionResult Commmon_Method(string VN, string Id)
{
return View(@"~/" + VN + ".cshtml");
}
}
查看页面:
$('#btn_Test').click(function () {
window.location.href = '@Url.Action("Commmon_Method", "Home")?Id=' + 1 + '&VN=' + 'Views/Test/Index2';
});
输出网址:-
http://localhost:52296/Home/Commmon_Method?Id=1&VN=Views/Test2/Index
--------------------------------- * ----------------- ----
即使我像基于MVC的动态路由一样尝试了自己,但未能成功:
http://localhost:52296/Home/Test2/Index
因此,控制器名称应为单个以提供所有请求,我也尝试了运行时控制器,而基于自定义的控制器未成功
我在MVC中成功实现了单个动态JSON数据方法,因此无需再编写代码束即可使用Jquery Ajax方法获取JSON数据。
在MVC中,只有基于单控制器的路由成功,这意味着MVC将是非常简单的开发应用程序,因此,您可以分享您的知识来简化复杂的开发方式吗?
答案 0 :(得分:0)
html:-
window.location.href = '@Url.Action("common_dll", "Home")?ctrl=Test';
用于创建Controller的Controller方法:
public ActionResult common_dll(string ctrl)
{
StringBuilder sb = new StringBuilder();
sb.Append("using System;" + Environment.NewLine);
sb.Append("using System.Collections.Generic;" + Environment.NewLine);
sb.Append("using System.Data;" + Environment.NewLine);
sb.Append("using System.Data.SqlClient;" + Environment.NewLine);
sb.Append("using System.Dynamic;" + Environment.NewLine);
sb.Append("using System.Linq;" + Environment.NewLine);
sb.Append("using System.Text;" + Environment.NewLine);
sb.Append("using System.Web.Mvc;" + Environment.NewLine);
sb.Append("namespace Testing_MVC.Controllers" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("public class " + ctrl + "Controller" + " : Controller" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("public ActionResult Index()" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("return View();" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
var dir = Server.MapPath("~\\Controllers");
var file = System.IO.Path.Combine(dir, ctrl + "Controller" + ".cs");
System.IO.Directory.CreateDirectory(dir);
System.IO.File.WriteAllText(file, sb.ToString());
return this.RedirectToAction("Index", ctrl, new { id = 1 });
}
答案 1 :(得分:0)
public static string JS_NAS(DataSet dss)
{
string str = Newtonsoft.Json.JsonConvert.SerializeObject(dss, Newtonsoft.Json.Formatting.Indented);
return str;
}
public static SqlParameter[] NAS_SQLPRM(string paramstr)
{
#region
string[] parameters = paramstr.Split('~');
string err = string.Empty;
int len = parameters.Length;
SqlParameter[] sqlParam = new SqlParameter[len];
for (int i = 0; i < len; i++)
{
string[] paramWithValue = parameters[i].Split('$');
string param = paramWithValue[0].ToString();
string value = paramWithValue[1].ToString();
sqlParam[i] = new SqlParameter { ParameterName = param, Value = value };
}
return sqlParam;
#endregion
}
[WebMethod]
public static String Insertupdates(string paramstr, string procname)
{
string err = "", dbstr = "";
string[] parameters = paramstr.Split('~');
int len = parameters.Length;
SqlParameter[] sqlParam = new SqlParameter[len];
for (int i = 0; i < len; i++)
{
string[] paramWithValue = parameters[i].Split('$');
string param = paramWithValue[0].ToString();
string value = paramWithValue[1].ToString();
sqlParam[i] = new SqlParameter { ParameterName = param, Value = value };
}
string str = new clsiCMSBLBase().insertData(ref err, ref dbstr, sqlParam, procname);
return err.Replace("$", "") + "$" + dbstr.Replace("$", "");
}
[WebMethod]
public static String GetRowData_Tables(string procedureName, string paramstr)
{
string[] parameters = paramstr.Split('~');
string err = string.Empty;
int len = parameters.Length;
SqlParameter[] sqlParam = new SqlParameter[len];
for (int i = 0; i < len; i++)
{
string[] paramWithValue = parameters[i].Split('$');
string param = paramWithValue[0].ToString();
string value = paramWithValue[1].ToString();
sqlParam[i] = new SqlParameter { ParameterName = param, Value = value };
}
try
{
DataSet ds = new clsiCMSBLBase().GetListData(ref err, sqlParam, procedureName);
String JSONString = String.Empty;
JSONString = Newtonsoft.Json.JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented);
return JSONString;
}
catch (Exception)
{
return "Error";
}
}
var data = getRowData_TableBased('DBSP_ListSupplierGroup', paramstr);
function create_Listgrid(data) {
var cellsrenderer = function (row, column, value) {
return '<div style="text-align: right; margin-top: 5px;">' + (1 + row) + '</div>';
}
$("#jqxgrid").jqxGrid(
{
width: '98%',
height: '370px',
source: { datatype: "json", datafields: [], localdata: data },
filterable: true,
sortable: true,
theme: 'energyblue',
pageable: true,
columnsresize: true,
pagesizeoptions: ['5', '10', '15', '20', '100'],
pagesize: 15,
pagermode: 'default',
enabletooltips: true,
columns: get_cols(data)
/*
columns: [
{ text: 'S.No', dataField: 'Slno', align: 'left', width: '40px', cellsrenderer: cellsrenderer },
{ text: 'MapID', dataField: 'MapID', align: 'left', hidden: true },
{ text: 'PriSupplierID', dataField: 'PriSupplierID', align: 'left', hidden: true },
{ text: "Primary Supp Code", datafield: "PriSuppCode", cellsalign: 'left', align: 'left', width: '140px' },
{ text: "Primary Supplier Name", datafield: "PriSupName", cellsalign: 'left', align: 'left', width: '420px' },
{ text: "Primary Supplier Type", datafield: "PriSupType", cellsalign: 'left', align: 'left', width: '125px', hidden: true },
{ text: 'SecSupplierID', dataField: 'SecSupplierID', align: 'left', hidden: true },
{ text: "Secondary Supplier Code", datafield: "SecSuppCode", cellsalign: 'left', align: 'left', width: '190px' },
{ text: "Secondary Supplier Name", datafield: "SecSupName", cellsalign: 'left', align: 'left', width: '420px' },
{ text: "SecSupType", datafield: "SecSupType", cellsalign: 'left', align: 'left', hidden: true }
]
*/
});
}
function get_cols(data) {
var datacols = new Array();
if (!isEmpty(data) && data.Table1.length > 0) {
$.each(data.Table1, function (name, v) {
if (v.ColumnWidth == 0)
datacols.push({ text: v.ColumnHeader, datafield: v.DataField, hidden: true });
else
datacols.push({ text: v.ColumnHeader, datafield: v.DataField, cellsalign: 'left', align: 'left', width: v.ColumnWidth });
});
$("#<%=btnExport.ClientID%>").show();
}
return datacols;
}
function getRowData_TableBased(procName, paramstr) {
var rowData;
$.ajax({
url: 'Supplier_Group.aspx/GetRowData_Tables',
type: "POST",
dataType: "json",
async: false,
data: "{procedureName: '" + procName + "',paramstr: '" + paramstr + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
var response = data.d;
if (response != "Error") {
rowData = $.parseJSON(response);
}
else {
alert("Retrive Error !!");
}
},
error: function (error) { }
});
return rowData;
}
/*
var paramstr = '';
paramstr = "@UserID$" + uid + '~';
paramstr += "@PageName$" + pgnm + '~';
*/
paramstr += "@MethodName$" + pgnm + '~';
paramstr += "@ErrorMsg$" + msg;
function fncCompareDates1(startDate, endDate) {
startDate = startDate.split('/');
endDate = endDate.split('/');
var new_start_date = new Date(startDate[2], startDate[1], startDate[0]);
var new_end_date = new Date(endDate[2], endDate[1], endDate[0]);
var date1 = startDate.split('/')[2] + "-" + startDate.split('/')[1] + "-" + startDate.split('/')[0];
var new_start_date = new Date(date1);
var date2 = endDate.split('/')[2] + "-" + endDate.split('/')[1] + "-" + endDate.split('/')[0];
var new_end_date = new Date(date2);
if (date_format(startDate) > date_format(endDate))
return false;
return true;
}
public static DataSet BIZ_LIST_DATA(ref string errString, SqlParameter[] parameters, string spname)
{
try
{
DataSet ds = new DataSet();
ds = DB_LIST_DATA(parameters, spname);
return ds;
}
catch (Exception ex)
{
errString = ex.Message;
}
return null;
}
public static DataSet DB_LIST_DATA(SqlParameter[] Params, string spName)
{
SqlConnection sqlCon = new SqlConnection(main.connectionStringICane());
try
{
DataSet ds = new DataSet();
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = sqlCon;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = spName;
foreach (SqlParameter p in Params)
{
if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
{
p.Value = DBNull.Value;
}
sqlCmd.Parameters.Add(p);
}
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCmd);
sqlDataAdapter.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlCon.Close();
sqlCon.Dispose();
}
}
function get_cols(data) {
var datacols = [];
if (!isEmpty(data)) {
$.each(data.Table1, function (name, value) {
if (value.ColumnWidth == 0)
datacols.push({ text: value.ColumnHeader, datafield: value.DataField, hidden: true });
else
datacols.push({ text: value.ColumnHeader, datafield: value.DataField, cellsalign: 'left', align: 'left', width: value.ColumnWidth });
});
}
return datacols;
}
function isEmpty(str) {
return typeof str == 'string' && !str.trim() || typeof str == 'undefined' || str === null || str == 0 || str == "" || str == "[]";
}
function getRowData_TableBased(procName, paramstr, urlpath) {
var rowData = '';
$.ajax({
url: urlpath,
type: "POST",
dataType: "json",
async: false,
data: "{procedureName: '" + procName + "',paramstr: '" + paramstr + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
rowData = data;
},
error: function (error) {
}
});
return rowData;
}
function Common_grid() {
var commonModuleOption = {
width: '97%',
height: '350',
filterable: true,
sortable: true,
theme: 'energyblue',
pageable: true,
columnsresize: true,
pagesizeoptions: ['5', '10', '15', '20', '100'],
pagesize: 15,
pagermode: 'default',
enabletooltips: true,
};
return commonModuleOption;
}
答案 2 :(得分:0)
public ActionResult Commmon_Method(string VN, string Id)
{
return View(@"~/" + VN + ".cshtml");
}
public ActionResult Commmon_Method_Url()
{
return PartialView(@"~/" + Request.QueryString["VN"] + ".cshtml");
}
[HttpPost]
public ActionResult GetRowData_Tables(string paramstr, string procedureName)
{
#region
string[] parameters = paramstr.Split('~');
string err = string.Empty;
int len = parameters.Length;
SqlParameter[] sqlParam = new SqlParameter[len];
for (int i = 0; i < len; i++)
{
string[] paramWithValue = parameters[i].Split('$');
string param = paramWithValue[0].ToString();
string value = paramWithValue[1].ToString();
sqlParam[i] = new SqlParameter { ParameterName = param, Value = value };
}
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(GetListData(ref err, sqlParam, procedureName), Newtonsoft.Json.Formatting.Indented));
#endregion
}
public DataSet GetListData(ref string errString, SqlParameter[] parameters, string spname)
{
#region
try
{
DataSet ds = new DataSet();
ds = ListData(parameters, spname);
return ds;
}
catch (Exception ex)
{
errString = ex.Message;
}
return null;
#endregion
}
public DataSet ListData(SqlParameter[] Params, string spName)
{
#region
String conString = System.Configuration.ConfigurationManager.ConnectionStrings["Connection2"].ConnectionString;
SqlConnection sqlCon = new SqlConnection(conString);
#region
try
{
DataSet ds = new DataSet();
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = sqlCon;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = spName;
foreach (SqlParameter p in Params)
{
if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
{
p.Value = DBNull.Value;
}
sqlCmd.Parameters.Add(p);
}
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCmd);
sqlDataAdapter.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlCon.Close();
sqlCon.Dispose();
}
#endregion
#endregion
}
//[OutputCache(Duration = 3600, VaryByParam = "none")]
public ActionResult LoadMenus()
{
#region
#region
var cntent = "";
DataSet dsmenus = new DataSet();
string error = "";
SqlParameter[] parameters = { new SqlParameter("@usid", SqlDbType.Int) { Value = 6 } };
dsmenus = new DALModel().populateDataSet(ref error, parameters, "DBSP_Get_Menu");
StringBuilder sb = new StringBuilder();
#endregion
sb.Append("<ul id='main-menu' class='sm sm-vertical sm-blue' data-smartmenus-id='15544681331245752'>");
if (dsmenus.Tables[0].Rows[0]["MenuID"].ToString() == "0" && dsmenus.Tables[0].Rows[0]["ParentID"].ToString() == "0")
{
cntent = "<ul></ul>";
}
else
{
#region
var ds = dsmenus.Tables[0].AsEnumerable().Where(r => r.Field<Int32>("ParentID") == Convert.ToInt32("0"));
foreach (DataRow pdr in ds)
{
var MenuID = Convert.ToInt32(pdr["MenuID"].ToString());
var Action = pdr["Action"].ToString();
var Controller = pdr["Controller"].ToString();
var MenuDesc = pdr["MenuDesc"].ToString();
sb.Append("<li>");
if (Action == "")
sb.Append("<a href='#'>" + MenuDesc + "</a>");
else
//sb.Append("<a href='" + Url.Action(Action, Controller, new { MenuId = MenuID }) + "'>" + "" + MenuDesc + "" + "</a>");
sb.Append("<a href='" + Url.Action("Commmon_Method_Url", "Home", new { VN = Action, ID = MenuID }) + "'>" + "" + MenuDesc + "" + "</a>");
sb = getSubMenuList(MenuID, dsmenus, sb);
sb.Append("</li>");
}
#endregion
}
sb.Append("</ul>");
cntent = sb.ToString();
return Content(cntent, "text/html");
#endregion
}
[OutputCache(Duration = 3600, VaryByParam = "none")]
public StringBuilder getSubMenuList(Int32 ParentID, DataSet ds, StringBuilder sb)
{
#region
try
{
var sm = ds.Tables[0].AsEnumerable().Where(r => r.Field<Int32>("ParentID") == ParentID);
Int32 cnt = sm.AsDataView<DataRow>().Count;
if (cnt > 0)
{
#region
sb.Append("<ul>");
foreach (DataRow subdr in sm)
{
var MenuID = Convert.ToInt32(subdr["MenuID"].ToString());
var Action = subdr["Action"].ToString();
var Controller = subdr["Controller"].ToString();
string MenuDesc = subdr["MenuDesc"].ToString().Replace(" ", "-");
sb.Append("<li>");
if (Action == "")
sb.Append("<a href='#'>" + MenuDesc + "</a>");
else
//sb.Append("<a href='" + Url.Action(Action, Controller, new { MenuId = MenuID }) + "'>" + MenuDesc + "</a>");
sb.Append("<a href='" + Url.Action("Commmon_Method_Url", "Home", new { VN = Action, ID = MenuID }) + "'>" + MenuDesc + "</a>");
sb = getSubMenuList(MenuID, ds, sb);
sb.Append("</li>");
}
sb.Append("</ul>");
#endregion
}
else
{
return sb;
}
}
catch (Exception ex)
{
throw ex;
}
return sb;
#endregion
}
public ActionResult common_dll(string ctrl, string View)
{
#region
StringBuilder sb = new StringBuilder();
sb.Append("using System;" + Environment.NewLine);
sb.Append("using System.Collections.Generic;" + Environment.NewLine);
sb.Append("using System.Data;" + Environment.NewLine);
sb.Append("using System.Data.SqlClient;" + Environment.NewLine);
sb.Append("using System.Dynamic;" + Environment.NewLine);
sb.Append("using System.Linq;" + Environment.NewLine);
sb.Append("using System.Text;" + Environment.NewLine);
sb.Append("using System.Reflection;" + Environment.NewLine);
sb.Append("using System.Reflection.Emit;" + Environment.NewLine);
sb.Append("using System.Web.Mvc;" + Environment.NewLine);
sb.Append("namespace Testing_MVC.Controllers" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("public class " + ctrl + "Controller" + " : Controller" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("public ActionResult " + View + "()" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("return View();" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
#endregion
#region
var dir = Server.MapPath("~\\Controllers");
var file = System.IO.Path.Combine(dir, ctrl + "Controller" + ".cs");
/*
System.IO.FileInfo fi = new System.IO.FileInfo(file);
System.IO.StreamWriter str = fi.CreateText();
str.WriteLine(sb.ToString());
str.Close();
*/
//System.IO.Directory.CreateDirectory(dir);
//System.IO.File.WriteAllText(file, sb.ToString());
if (System.IO.File.Exists(file))
System.IO.File.Delete(file);
System.IO.File.AppendAllLines(file, sb.ToString().Split(Environment.NewLine.ToCharArray()).ToList<string>());
/*
System.IO.FileInfo fi = new System.IO.FileInfo(file);
System.IO.StreamWriter str = fi.CreateText();
str.WriteLine(sb.ToString());
str.Close();
*/
#endregion
return this.RedirectToAction(View, ctrl, new { MainID = 12, ID = 1 });
}
答案 3 :(得分:0)
<script>
$('#btn_Test').click(function () {
window.location.href = '@Url.Action("common_dll", "Home")?ctrl=Testing&View=Index';
//window.location.href = '@Url.Action("Commmon_Method", "Home")?Id=' + 1 + '&VN=' + 'Areas/Testing/Views/Index';
});
</script>
<script>
//$(function () {
// var paramstr = '';
// paramstr = "@@Month$" + 1;
// paramstr += "~@@Year$" + 2018;
// paramstr += "~@@StateID$" + 0;
// paramstr += "~@@HubID$" + 0;
// paramstr += "~@@BranchID$" + 0;
// paramstr += "~@@EmpID$" + 0;
// paramstr += "~@@EmpTypeID$" + 0;
// paramstr += "~@@UserID$" + 1;
// paramstr += "~@@UserTypeID$" + 1;
// var data = getRowData_TableBased('DBSP_MM_Rpt_AttendanceMonthWsie', paramstr, '@Url.Action("GetRowData_Tables", "Home")');
// Grid(data);
//});
function Grid(data) {
if (!isEmpty(data)) {
//$("#jqxgrid").jqxGrid($.extend(true, {}, Common_grid(), {
// source: { datatype: "json", datafields: [], localdata: data },
// columns: Get_Colmns(data)
//}));
}
}
function Get_Colmns(data) {
var datacols = [];
if (!isEmpty(data)) {
$.each(data.Table1, function (name, value) {
if (value.ColumnWidth == 0)
datacols.push({ text: value.ColumnHeader, datafield: value.DataField, hidden: true });
else
datacols.push({ text: value.ColumnHeader, datafield: value.DataField, cellsalign: 'left', align: 'left', width: value.ColumnWidth });
});
}
return datacols;
}
</script>
答案 4 :(得分:0)
<script>
$('#btn_Controller1').click(function () {
window.location.href = '@Url.Action("common_dll", "Home")?ctrl=Testing&View=Index';
//window.location.href = '@Url.Action("Commmon_Method", "Home")?Id=' + 1 + '&VN=' + 'Views/Test/Index';
//window.location.href = '@Url.Action("common_dll", "Home")?ctrl=List&View=Index';
});
$('#btn_Controller2').click(function () {
window.location.href = '@Url.Action("common_dll", "Home")?ctrl=MyDocs&View=Test';
});
$('#btn_Controller3').click(function () {
window.location.href = '@Url.Action("common_dll", "Home")?ctrl=Test&View=Delete';
});
$('#btn_Controller4').click(function () {
window.location.href = '@Url.Action("common_dll", "Home")?ctrl=Test1&View=Index';
});
$('#btn_Controller5').click(function () {
window.location.href = '@Url.Action("common_dll", "Home")?ctrl=Test2&View=Index';
});
$('#btn_Controller6').click(function () {
window.location.href = '@Url.Action("common_dll", "Home")?ctrl=Test3&View=Index';
});
</script>