本文整理汇总了C#中System.Web.Mvc.ContentResult类的典型用法代码示例。如果您正苦于以下问题:C# ContentResult类的具体用法?C# ContentResult怎么用?C# ContentResult使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ContentResult类属于System.Web.Mvc命名空间,在下文中一共展示了ContentResult类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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;
}
}
}
示例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;
}
示例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;
}
示例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 };
}
}
示例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;
}
示例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;
}
}
}
示例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;
}
}
示例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;
}
示例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
};
}
}
示例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;
}
示例11: Projekte
public ActionResult Projekte ()
{
ContentResult Result = new ContentResult();
Result.Content = MapWrapper.MapDataWrapper.Instance.CreateOSMPhasenOrientedLocations
(WordUp23.Basics.ShowDatenTyp.Projekt);
return Result;
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
}