本文整理汇总了C#中System.Web.Mvc.ContentResult类的典型用法代码示例。如果您正苦于以下问题:C# ContentResult类的具体用法?C# ContentResult怎么用?C# ContentResult使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ContentResult类属于System.Web.Mvc命名空间,在下文中一共展示了ContentResult类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: OnAuthorization
public void OnAuthorization(AuthorizationContext filterContext)
{
if (!Client.IsLogin)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
ContentResult cr = new ContentResult();
cr.Content = "{msg:'forbidden',isLogin:'false'}";
filterContext.Result = cr;
}
else
{
filterContext.HttpContext.Response.Redirect(C.APP);
}
}
if (requireAdmin && Client.IsLogin)
{
if (!Client.IsAdministrator)
{
ContentResult cr = new ContentResult();
cr.Content = "{msg:'forbidden to access',isLogin:'true',isAdmin:'false'}";
filterContext.Result = cr;
}
}
}
开发者ID:Xiaoyuyexi,项目名称:LMS,代码行数:26,代码来源:CustomAuthorize.cs
示例2: GetAnswer
public ActionResult GetAnswer(string researchIdName,int skip)
{
var content = new ContentResult() { ContentEncoding = System.Text.Encoding.UTF8 };
content.Content = GoocaBoocaDataModels.Utility.CrossTableConvert.CreateAnswerData(researchIdName,skip);
return content;
}
开发者ID:kiichi54321,项目名称:GoocaBoocaBase,代码行数:7,代码来源:DataController.cs
示例3: OnActionExecuting
/// <summary>
/// Called before an action method executes.
/// </summary>
/// <param name="filterContext">The filter context.</param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Continue normally if the model is valid.
if (filterContext == null || filterContext.Controller.ViewData.ModelState.IsValid)
{
return;
}
var serializationSettings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
// Serialize Model State for passing back to AJAX call
var serializedModelState = JsonConvert.SerializeObject(
filterContext.Controller.ViewData.ModelState,
serializationSettings);
var result = new ContentResult
{
Content = serializedModelState,
ContentType = "application/json"
};
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
filterContext.Result = result;
}
开发者ID:targitaj,项目名称:m3utonetpaleyerxml,代码行数:31,代码来源:FormValidatorAttribute.cs
示例4: ImagenSizeValidation
public virtual JsonResult ImagenSizeValidation(HttpPostedFileBase fileToUpload)
{
try
{
Session["ImagenFile"] = null;
var result = new ContentResult();
string resp = "No Eligio ningun Archivo";
//Parametro parametro = new Parametro();
var parametro = 100000; // ParametroNegocio.GetParameById("MaxImageSizeUpload", marketid);
int imagesize = 1024;
int size = int.MinValue;
if (parametro != null && !string.IsNullOrEmpty(parametro.ToString()))
{
bool esnum = Int32.TryParse(parametro.ToString(), out size);
if (esnum)
imagesize = size;
}
if (fileToUpload != null)
{
if (!fileToUpload.ContentType.Contains("image"))
{
resp = "Tipo de archivo no valido!";
return new JsonResult { Data = resp, ContentType = "text/html" };
}
if (fileToUpload.ContentLength > (imagesize * 1000))
{
resp = LenceriaKissy.Recursos.AppResources.Vistas.MaxImageSize + " " + parametro + " KB.";
}
else
{
int nFileLen = fileToUpload.ContentLength;
byte[] resultado = new byte[nFileLen];
fileToUpload.InputStream.Read(resultado, 0, nFileLen);
//Session.Add("ImagenFile", resultado);
Session["ExtensionImagen"] = fileToUpload.ContentType.Split('/')[1];
resp = LenceriaKissy.Recursos.AppResources.Vistas.OK;
}
}
if (resp == LenceriaKissy.Recursos.AppResources.Vistas.OK)
{
string newFileName = Guid.NewGuid().ToString().Trim().Replace("-", "") + System.IO.Path.GetExtension(fileToUpload.FileName);
var fileName = this.Server.MapPath("~/uploads/" + System.IO.Path.GetFileName(newFileName));
fileToUpload.SaveAs(fileName);
Session["ImagenFile"] = "/uploads/" + System.IO.Path.GetFileName(newFileName);
}
return new JsonResult { Data = resp, ContentType = "text/html", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
catch (Exception ex)
{
return new JsonResult { Data = ex.Message, ContentType = "text/html", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
开发者ID:polmereles,项目名称:1601,代码行数:60,代码来源:FileUploadController.cs
示例5: GetTree
public ContentResult GetTree()
{
ContentResult contentResult = new ContentResult();
string strSql = Request.QueryString["sql"];
if (strSql.Trim().Contains(" "))
{
throw new Exception("参数“sql”格式错误!");
}
var dtTree = _dba.QueryDataTable(strSql);
List<TreeModel> lsTree = new List<TreeModel>();
foreach (DataRow row in dtTree.Rows)
{
lsTree.Add(new TreeModel()
{
id = row["id"].ToString(),
parentId = row["parentId"].ToString(),
text = row["text"].ToString(),
state = TreeModel.State.open.ToString()
});
}
contentResult.Content = Newtonsoft.Json.JsonConvert.SerializeObject(TreeModel.ToTreeModel(lsTree));
return contentResult;
}
开发者ID:weibin268,项目名称:Zhuang.UPMS,代码行数:28,代码来源:EasyUIController.cs
示例6: OnActionExecuting
public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.Controller.ViewData.ModelState.IsValid)
{
if (filterContext.HttpContext.Request.HttpMethod == "GET")
{
var result = new HttpStatusCodeResult(HttpStatusCode.BadRequest);
filterContext.Result = result;
}
else
{
var result = new ContentResult();
string content = JsonConvert.SerializeObject(filterContext.Controller.ViewData.ModelState,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
result.Content = content;
result.ContentType = "application/json";
filterContext.HttpContext.Response.StatusCode = 400;
filterContext.Result = result;
}
}
}
开发者ID:DejanMilicic,项目名称:FastPrototypingFramework,代码行数:25,代码来源:ValidatorActionFilter.cs
示例7: Create
public ContentResult Create(string json)
{
OdbcConnection hiveConnection = new OdbcConnection("DSN=Hadoop Server;UID=hadoop;PWD=hadoop");
hiveConnection.Open();
Stream req = Request.InputStream;
req.Seek(0, SeekOrigin.Begin);
string request = new StreamReader(req).ReadToEnd();
ContentResult response;
string query;
try
{
query = "INSERT INTO TABLE error_log (json_error_log) VALUES('" + request + "')";
OdbcCommand command = new OdbcCommand(query, hiveConnection);
command.ExecuteNonQuery();
command.CommandText = query;
response = new ContentResult { Content = "{status: 1}", ContentType = "application/json" };
hiveConnection.Close();
return response;
}
catch(WebException error)
{
response = new ContentResult { Content = "{status: 0, message:" + error.Message.ToString()+ "}" };
System.Diagnostics.Debug.WriteLine(error.ToString());
hiveConnection.Close();
return response;
}
}
开发者ID:Elang89,项目名称:HadoopWebService,代码行数:29,代码来源:LogsController.cs
示例8: Process
public ActionResult Process(HttpRequestBase request, ModelStateDictionary modelState)
{
PdtVerificationBinder binder = new PdtVerificationBinder();
Transaction tx = binder.Bind(request.Form, modelState);
ContentResult cr = new ContentResult();
cr.ContentEncoding = Encoding.UTF8;
cr.ContentType = "text/html";
cr.Content = "FAIL\n";
if (tx != null)
{
Transaction dbTx = m_txRepository.GetAll().Where(x => x.Tx == tx.Tx).FirstOrDefault();
if (dbTx != null && dbTx.AuthToken == tx.AuthToken)
{
StringBuilder sb = new StringBuilder();
sb.Append("SUCCESS\n");
sb.Append(BuildContent(dbTx));
cr.Content = sb.ToString();
}
}
return cr;
}
开发者ID:triggerfish,项目名称:PayPalEmulator,代码行数:25,代码来源:AuthorisePdtHandler.cs
示例9: StartDatabaseBackup
public ActionResult StartDatabaseBackup()
{
try
{
var dc = new ProcurementDataClassesDataContext(ConfigurationManager.ConnectionStrings["BidsForKidsConnectionString"].ConnectionString);
var result = new ContentResult();
var backupLocation = ConfigurationManager.AppSettings["SQLBackupLocation"];
if (string.IsNullOrEmpty(backupLocation) == true)
{
throw new ApplicationException("SQLBackupLocation is not set in web.config");
}
dc.BackupDatabase(backupLocation);
result.Content = "Database has been backed up.";
return result;
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return new ContentResult
{
Content = "Error backing up database: " + ex.Message
};
}
}
开发者ID:codereflection,项目名称:BidsForKids,代码行数:30,代码来源:AdminController.cs
示例10: GenerateDonorReport
public ActionResult GenerateDonorReport(DonorReportSetupVideModel reportSetup)
{
var donors = reportSetup.AuctionYearFilter == 0 ?
Mapper.Map<IEnumerable<Donor>, IEnumerable<DonorReportViewModel>>(repo.GetDonors()).ToList()
:
Mapper.Map<IEnumerable<Donor>, IEnumerable<DonorReportViewModel>>(repo.GetDonors(reportSetup.AuctionYearFilter)).ToList();
donors = ApplyDonorFilters(donors, reportSetup);
if (reportSetup.BusinessType == false)
donors.Where(x => x.DonorType == "Business").ToList().ForEach(x => donors.Remove(x));
if (reportSetup.ParentType == false)
donors.Where(x => x.DonorType == "Parent").ToList().ForEach(x => donors.Remove(x));
var reportHtml = new StringBuilder();
reportHtml.AppendLine("<h3>" + reportSetup.ReportTitle + "</h3>");
reportHtml.AppendLine("<table class=\"customReport\">");
reportHtml.AppendLine("<tbody>");
var selectedColumns = GetSelectedColumns(reportSetup);
BuildHeaders(selectedColumns, reportHtml, reportSetup.IncludeRowNumbers);
BuildReportBody(selectedColumns, donors, reportHtml, reportSetup.IncludeRowNumbers);
reportHtml.AppendLine("</tbody>");
reportHtml.AppendLine("</table>");
var result = new ContentResult() { Content = reportHtml.ToString() };
return result;
}
开发者ID:codereflection,项目名称:BidsForKids,代码行数:34,代码来源:ReportGenController.cs
示例11: Projekte
public ActionResult Projekte ()
{
ContentResult Result = new ContentResult();
Result.Content = MapWrapper.MapDataWrapper.Instance.CreateOSMPhasenOrientedLocations
(WordUp23.Basics.ShowDatenTyp.Projekt);
return Result;
}
开发者ID:heinzsack,项目名称:DEV,代码行数:7,代码来源:HomeController.cs
示例12: Edit
public ContentResult Edit(string id, string value)
{
var a = id.Split('.');
var c = new ContentResult();
c.Content = value;
var p = DbUtil.Db.Programs.SingleOrDefault(m => m.Id == a[1].ToInt());
if (p == null)
return c;
switch (a[0])
{
case "ProgramName":
p.Name = value;
break;
case "RptGroup":
p.RptGroup = value;
break;
case "StartHours":
p.StartHoursOffset = value.ToDecimal();
break;
case "EndHours":
p.EndHoursOffset = value.ToDecimal();
break;
}
DbUtil.Db.SubmitChanges();
return c;
}
开发者ID:vs06,项目名称:bvcms,代码行数:26,代码来源:ProgramController.cs
示例13: Process
public ActionResult Process(HttpRequestBase request, ModelStateDictionary modelState)
{
IpnVerificationBinder binder = new IpnVerificationBinder();
Transaction tx = binder.Bind(request.Form, modelState);
ContentResult cr = new ContentResult();
cr.ContentEncoding = Encoding.UTF8;
cr.ContentType = "text/html";
cr.Content = "INVALID";
if (tx != null)
{
Transaction dbTx = m_txRepository.GetAll().Where(x => x.Tx == tx.Tx).FirstOrDefault();
if (dbTx != null)
{
string expected = dbTx.ToIpnQueryString().ToString();
QueryString actualQs = new QueryString();
actualQs.Add(request.Form);
actualQs.Remove("cmd");
string actual = actualQs.ToString();
if (expected == actual)
{
cr.Content = "VERIFIED";
}
}
}
return cr;
}
开发者ID:triggerfish,项目名称:PayPalEmulator,代码行数:30,代码来源:AuthoriseIpnHandler.cs
示例14: GetEmployees
// GET: Employee
public ActionResult GetEmployees()
{
List<EmployeeVM> list = new List<EmployeeVM>()
{
new EmployeeVM()
{
FullName = "Alper Dortbudak"
},
new EmployeeVM()
{
FullName = "Connor Dortbudak"
}
};
var camelCaseFormatter = new JsonSerializerSettings();
camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
var jsonResult = new ContentResult
{
Content = JsonConvert.SerializeObject(list, camelCaseFormatter),
ContentType = "application/json"
};
return jsonResult;
}
开发者ID:adortbudak,项目名称:AngularForMVC,代码行数:26,代码来源:EmployeeController.cs
示例15: HttpWebResponseResult
/// <summary>
/// Relays an HttpWebResponse as verbatim as possible.
/// </summary>
/// <param name="responseToRelay">The HTTP response to relay.</param>
public HttpWebResponseResult(HttpWebResponse responseToRelay)
{
if (responseToRelay == null) {
throw new ArgumentNullException("response");
}
_response = responseToRelay;
Stream contentStream;
if (responseToRelay.ContentEncoding.Contains("gzip")) {
contentStream = new GZipStream(responseToRelay.GetResponseStream(), CompressionMode.Decompress);
} else if (responseToRelay.ContentEncoding.Contains("deflate")) {
contentStream = new DeflateStream(responseToRelay.GetResponseStream(), CompressionMode.Decompress);
} else {
contentStream = responseToRelay.GetResponseStream();
}
if (string.IsNullOrEmpty(responseToRelay.CharacterSet)) {
// File result
_innerResult = new FileStreamResult(contentStream, responseToRelay.ContentType);
} else {
// Text result
var contentResult = new ContentResult();
contentResult = new ContentResult();
contentResult.Content = new StreamReader(contentStream).ReadToEnd();
_innerResult = contentResult;
}
}
开发者ID:jonfreeland,项目名称:LogglyJavaScriptProxy,代码行数:32,代码来源:LogglyProxyController.cs
示例16: DeleteBlobs
public ActionResult DeleteBlobs()
{
IContentRepository repo = ServiceLocator.Current.GetInstance<IContentRepository>();
BlobFactory blobFactory = ServiceLocator.Current.GetInstance<BlobFactory>();
var assetHelper = ServiceLocator.Current.GetInstance<ContentAssetHelper>();
StringBuilder sb = new StringBuilder();
IEnumerable<ContentReference> contentReferences = null;
contentReferences = repo.GetDescendents(EPiServer.Core.ContentReference.GlobalBlockFolder);
DeleteBlobs(contentReferences, repo, sb, blobFactory);
DeleteContentInAssetFolders(contentReferences, assetHelper, repo, sb, blobFactory);
contentReferences = repo.GetDescendents(EPiServer.Core.ContentReference.SiteBlockFolder);
DeleteBlobs(contentReferences, repo, sb, blobFactory);
DeleteContentInAssetFolders(contentReferences, assetHelper, repo, sb, blobFactory);
// Private page folders too
contentReferences = repo.GetDescendents(EPiServer.Core.ContentReference.StartPage);
DeleteContentInAssetFolders(contentReferences, assetHelper, repo, sb, blobFactory);
ContentResult result = new ContentResult();
result.Content = sb.ToString();
return result;
}
开发者ID:smchristenson,项目名称:CommerceStarterKit,代码行数:25,代码来源:DeveloperToolsController.cs
示例17: Play
public ActionResult Play()
{
ViewData["PageTitle"] = "人人翁 主游戏";
RecordFromPage rfp = new RecordFromPage();
int pageindex = 1;
int type = 1;
rfp.ConnStr = DBHelper.ConnStr;
rfp.TableName = "T_Game";
rfp.PageIndex = pageindex;
rfp.Where = " F_Type=" + type.ToString();
rfp.Fields = "*";
rfp.OrderFields = "F_Phases desc";
rfp.PageSize = 20;
DataTable dt=rfp.GetDt();
if (dt == null || dt.Rows.Count == 0)
{
ContentResult cr = new ContentResult();
cr.ContentType = "text/html";
cr.Content = "Table NULL";
return cr;
}
if(pageindex==1)
{
for(int i=0;i<3;i++)
{
DataRow dr= dt.NewRow();
dr["F_Phases"]=Convert.ToInt32(dt.Rows[0]["F_Phases"])+1;
dr["F_LotteryDate"]=Convert.ToDateTime(dt.Rows[0]["F_LotteryDate"]).AddMinutes(3);
dr["F_NumOne"]=0;
dr["F_NumTwo"]=0;
dr["F_NumThree"]=0;
dr["F_Bonus"]=0;
dr["F_Id"]=0;
dr["F_InvolvedNum"]=0;
dr["F_WinningNum"]=0;
dr["F_Lottery"]=false;
dt.Rows.InsertAt(dr,0);
}
}
string defimgattr = " border='0' align='absmiddle' width='18' height='21' style='display:inline'";
switch (type)
{
case 1:
ViewData["LotteryShow"] = "<img " + defimgattr + " src='../Content/numimg/0{0}.jpg'> + <img " + defimgattr + " src='../Content/numimg/0{1}.jpg'>+<img " + defimgattr + " src='../Content/numimg/0{2}.jpg'>=<img " + defimgattr + " src='../Content/numimg/{3}.jpg'>";
break;
case 2:
ViewData["LotteryShow"] = " {0}X{1}X{2}X{3}";
break;
default:
ViewData["LotteryShow"] = "{0}-{1}-{2}-{3}";
break;
}
ViewData["GameType"] = type.ToString();
ViewData["ConentTable"] = dt;
return View();
}
开发者ID:cj1324,项目名称:hanchenproject,代码行数:60,代码来源:HomeController.cs
示例18: Edit
public ContentResult Edit(string id, string value)
{
var a = id.Split('.');
var c = new ContentResult();
c.Content = value;
if (a[1] == value)
return c;
var existingrole = DbUtil.Db.Roles.SingleOrDefault(m => m.RoleName == value);
var role = DbUtil.Db.Roles.SingleOrDefault(m => m.RoleName == a[1]);
if (role == null)
{
TempData["error"] = "no role";
return Content("/Error/");
}
if (existingrole != null && existingrole.RoleName != role.RoleName)
{
TempData["error"] = "duplicate role";
return Content("/Error/");
}
switch (a[0])
{
case "RoleName":
role.RoleName = value;
break;
}
DbUtil.Db.SubmitChanges();
return c;
}
开发者ID:rossspoon,项目名称:bvcms,代码行数:28,代码来源:RolesController.cs
示例19: GameTimer
public ActionResult GameTimer()
{
ContentResult cres = new ContentResult();
cres.ContentType = "text/html";
string cont = null;
string game = Request.Form["gtype"].ToString();
switch (Convert.ToInt32(game))
{
case 1:
cont = "GameOneTimer";
break;
case 2:
cont = "GameTwoTimer";
break;
default:
cont = "ERROR";
break;
}
HttpContext.Application.Lock();
if (HttpContext.Application[cont] != null)
{
cont = HttpContext.Application[cont].ToString();
}
HttpContext.Application.UnLock();
Manage_T_Game mtg = new Manage_T_Game();
int pid = mtg.GetNewPhases(Convert.ToInt32(game));
cres.Content ="{\"id\":\""+pid.ToString()+"\",\"timer\":\""+cont+"\"}";
return cres;
}
开发者ID:cj1324,项目名称:hanchenproject,代码行数:32,代码来源:AjaxController.cs
示例20: GetNextDocumentCommand
/// <summary>
///
/// </summary>
/// <param name="costCentreApplicationId"></param>
/// <param name="lastDeliveredCommandRouteItemId">-1 if never requested before</param>
/// <returns></returns>
public ActionResult GetNextDocumentCommand(Guid costCentreApplicationId, long lastDeliveredCommandRouteItemId)
{
_log.InfoFormat("GetNextDocumentCommand from CCAPPId : {0} with lastDeliveredCommandRouteItemId : {1}", costCentreApplicationId, lastDeliveredCommandRouteItemId);
Guid ccid = _costCentreApplicationService.GetCostCentreFromCostCentreApplicationId(costCentreApplicationId);
DocumentCommandRoutingResponse response = null;
try
{
if (_costCentreApplicationService.IsCostCentreActive(costCentreApplicationId))
response = _commandRouterResponseBuilder.GetNextDocumentCommand(costCentreApplicationId, ccid, lastDeliveredCommandRouteItemId);
else
response = new DocumentCommandRoutingResponse { ErrorInfo = "Inactive CostCentre Application Id" };
}
catch (Exception ex )
{
response = new DocumentCommandRoutingResponse { ErrorInfo = "Failed to get next document command" };
_log.InfoFormat("ERROR GetNextDocumentCommand from CCAPPId : {0} with lastDeliveredCommandRouteItemId : {1}", costCentreApplicationId, lastDeliveredCommandRouteItemId);
_log.Error(ex);
}
ContentResult result = new ContentResult
{
Content = JsonConvert.SerializeObject(response),
ContentType = "application/json",
ContentEncoding = Encoding.UTF8
};
AuditCCHit(ccid, "GetNextDocumentCommand", result.Content, "OK" );
return result;
}
开发者ID:asanyaga,项目名称:BuildTest,代码行数:34,代码来源:CommandRoutingController.cs
注:本文中的System.Web.Mvc.ContentResult类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论