Viewbag doesn't exist - asp.net-mvc-4

I tried to do this:
var NewViewResult = new ViewResult { ViewName = "Error", ViewBag.error = "Error Here" };
I got these two errors
Invalid initializer member declarator
The name 'ViewBag' does not exist in the current context
That is my code:
public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled) return;
string actionName = filterContext.RouteData.Values["action"].ToString();
Type controllerType = filterContext.Controller.GetType();
var method = controllerType.GetMethod(actionName);
var returnType = method.ReturnType;
if (returnType.Equals(typeof(JsonResult))) if (filterContext.Exception is CustomException) filterContext.Result = new JsonResult() { Data = ((CustomException)filterContext.Exception).Type }; else filterContext.Result = new JsonResult() { Data = OurExceptionType.GeneralException };
else if (returnType.Equals(typeof(ActionResult)) || (returnType).IsSubclassOf(typeof(ActionResult))) filterContext.Result = new ViewResult { ViewName = "Error" ViewBag.error="SomeError" };
filterContext.ExceptionHandled = true;
}

ViewBag is a dynamic property you cannot pass it like this in a ViewResult.
Set value in ViewBag like this:
var NewViewResult = new ViewResult { ViewName = "Error" };
ViewBag.error = "Error Message";
and In View, you can simply access it without passing in the ViewResult:
<span>#ViewBag.error</span>
and if you really want to pass it in ViewResult,then don't use ViewBag, do like this:
var NewViewResult = new ViewResult { ViewName = "Error" };

Related

Deleting one object from CartItems in razor pages

i have some products in my Cart via cookies, now i want to select and delete them from cart,
public class CartModel : PageModel
{
public List<CartItem> CartItems;
public const string CookieName = "cart-items";
public void OnGet()
{
var serializer = new JavaScriptSerializer();
var value = Request.Cookies[CookieName];
CartItems = serializer.Deserialize<List<CartItem>>(value); //error accurred in this line
foreach (var item in CartItems)
item.TotalItemPrice = item.UnitPrice * item.Count;
}
public IActionResult OnGetRemoveFromCart(long id)
{
var serializer = new JavaScriptSerializer();
var value = Request.Cookies[CookieName];
Response.Cookies.Delete(CookieName);
var cartItems = serializer.Deserialize<List<CartItem>>(value);
var itemToRemove = cartItems.FirstOrDefault(x => x.Id == id);
cartItems.Remove(itemToRemove);
var options = new CookieOptions { Expires = DateTime.Now.AddDays(2) };
Response.Cookies.Append(CookieName, serializer.Serialize(cartItems), options);
return RedirectToPage("/Cart");
}
until i don't click on the delete button, everything is ok, i don't have any error in OnGet on Cart Razor page. but when i click on the delete button and OnGetRemoveFromCart's handler is executed,CartItems is null on OnGet!
the errorr: 'Object reference not set to an instance of an object.CartItems was null.'
Response.Cookies.Delete(CookieName);
You delete the cookie in the OnGetRemoveFromCart handler, so value becomes null in the OnGet handler. You should always check for null before accessing cookie values:
public void OnGet()
{
var serializer = new JavaScriptSerializer();
var value = Request.Cookies[CookieName];
if(value is not null)
{
CartItems = serializer.Deserialize<List<CartItem>>(value);
foreach (var item in CartItems)
{
item.TotalItemPrice = item.UnitPrice * item.Count;
}
}
}

ASP .Net Core file upload - getting form data when [DisableFormValueModelBinding] attribute is in place

I went ahead and implemented an ASP .Net Core file upload controller per the documentation and it requires using a [DisableFormValueModelBinding] attribute for streaming large files. I got that working fine. Unfortunately, when using that attribute it seems to block my JSON properties coming in from the form.
Is there any way to get both the file and the form data here? Here is my controller code (the request.form calls are where I am having issues):
[Route("{caseNbr:int}/Document")]
[ResponseType(typeof(CaseDocumentModel))]
[DisableFormValueModelBinding]
[HttpPost]
public async Task<IActionResult> PostDocument(int caseNbr)
{
string errorTrackingFileName = string.Empty;
try
{
UserSessionModel userSessionModel = SessionExtensions.CurrentUserSession;
if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
{
return BadRequest("Bad Request");
}
var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit);
var reader = new MultipartReader(boundary, HttpContext.Request.Body);
var section = await reader.ReadNextSectionAsync();
while (section != null)
{
var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
if (hasContentDispositionHeader)
{
if (!MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
{
return BadRequest("Bad Request");
}
var fileName = WebUtility.HtmlEncode(contentDisposition.FileName.Value);
errorTrackingFileName = fileName;
var trustedFileNameForFileStorage = fileName; //Path.GetRandomFileName();
var streamedFileContent = await FileHelpers.ProcessStreamedFile(section, contentDisposition, ModelState, _permittedExtensions, _fileSizeLimit);
if (!ModelState.IsValid)
{
return BadRequest("Bad Request");
}
using (var targetStream = System.IO.File.Create(Path.Combine(_tempFilePath, trustedFileNameForFileStorage)))
{
await targetStream.WriteAsync(streamedFileContent);
**//This is where I am having trouble:**
string descrip = HttpContext.Request.Form["Description"].ToString();
string docType = HttpContext.Request.Form["DocType"].ToString() ?? "Document";
bool isGeneralFileUpload = false;
if (string.IsNullOrWhiteSpace(Request.Form["GeneralFileUpload"]) == false && AppHelper.IsBool(Request.Form["GeneralFileUpload"]))
isGeneralFileUpload = bool.Parse(Request.Form["GeneralFileUpload"]);
int transcriptionJobId = 0;
if (string.IsNullOrWhiteSpace(Request.Form["TranscriptionJobId"]) == false && AppHelper.IsNumeric(Request.Form["TranscriptionJobId"]))
transcriptionJobId = int.Parse(Request.Form["TranscriptionJobId"]);
CaseDocumentModel createdCaseDocumentModel;
if (docType.Equals("Dictation"))
createdCaseDocumentModel = DictationRepository.ProcessDictationFile(userSessionModel.DBID, caseNbr, _tempFilePath, fileName, userSessionModel);
else if (isGeneralFileUpload)
createdCaseDocumentModel = DashboardAdjusterRepository.CreateGeneralFileUploadDocument(_tempFilePath, fileName, userSessionModel, docType, descrip);
else if (docType.Equals("Transcription"))
createdCaseDocumentModel = TranscriptionRepository.UploadTranscriptionFile(userSessionModel.DBID, _tempFilePath, fileName, userSessionModel, transcriptionJobId);
else
createdCaseDocumentModel = CaseRepository.CreateCaseDocumentRecord(userSessionModel.DBID, caseNbr, descrip, docType, _tempFilePath, fileName, userSessionModel);
return Ok(createdCaseDocumentModel);
}
}
// Drain any remaining section body that hasn't been consumed and
// read the headers for the next section.
section = await reader.ReadNextSectionAsync();
}
}
catch (Exception ex)
{
AppHelper.WriteErrorLog("CaseController PostDocument failed due to " + ex.Message + " case number was " + caseNbr + " file name was " + errorTrackingFileName);
return BadRequest("Bad Request");
}
return BadRequest("Bad Request");
}
Here is a sample call with Postman:
Screen shot of Postman

Sending emaills with template MVC using Razor

I want to send some mails from my site.
I've created a template: OrderPlacedEmail.cshtml
#model OnlineCarStore.Models.PurchaseVM
<h1>Order Placed Email Notification</h1>
<p>#Model.Comments</p>
Dear #Model.Name,
<h2>Thank you.</h2>
<p>
You’ve made a purchase on #Model.Comments
</p>....and so on...
I've created a view model, and I use it like this:
var template = Server.MapPath("~/Templates/OrderPlaced.cshtml");
var viewModel = new PurchaseVM
{
GuId = new Guid(guidValue),
Name = name,
Address = address,
Phone = phone,
Email = email,
Comments = comments,
Date = DateTime.Now,
CartList = cartList
};
var body = Razor.Parse(template, viewModel);
As I understood, the Razor.Parse method, should replace all the details from my template with the values from view model. But, the body gets the value of the location of the template, as you can see below:
Can you please advise what I'm doing wrong.
If you wish there is a helper that i use
public static class HtmlOutputHelper
{
public static string RenderViewToString(ControllerContext context,
string viewPath,
object model = null,
bool partial = false)
{
// first find the ViewEngine for this view
ViewEngineResult viewEngineResult = null;
if (partial)
viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
else
viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);
if (viewEngineResult == null)
throw new FileNotFoundException("View cannot be found.");
// get the view and attach the model to view data
var view = viewEngineResult.View;
context.Controller.ViewData.Model = model;
string result = null;
using (var sw = new StringWriter())
{
var ctx = new ViewContext(context, view,
context.Controller.ViewData,
context.Controller.TempData,
sw);
view.Render(ctx, sw);
result = sw.ToString();
}
return result;
}
}
On your controller
var viewModel = new PurchaseVM
{
GuId = new Guid(guidValue),
Name = name,
Address = address,
Phone = phone,
Email = email,
Comments = comments,
Date = DateTime.Now,
CartList = cartList
};
var emailTemplate = "~/Views/Templates/OrderPlaced.cshtml";
var emailOutput = HtmlOutputHelper.RenderViewToString(ControllerContext, emailTemplate, emailModel, false);
You also can use ActionMailerNext lib from NuGet Gallery for this scenario.
public class EmailController : MailerBase
{
//...
public EmailResult OrderPlaced(Order order)
{
MailAttributes.To.Add(new MailAddress("to#email.com"));
MailAttributes.From = new MailAddress("from#email.com");
return Email("OrderPlaced", new PurchaseVM
{
//...
});
}
//...
}
You can leave your View unchanged.

FileStream openAsync throws Error #1009

hi I have a problem regarding FileStream openAsync read file, I have a listener and waiting on complete
var file:File = File.applicationStorageDirectory.resolvePath(fName+'.'+EXT);
var fileStream:FileStream = new FileStream();
if (!file.exists) {
this.dispatchEvent(new AppEvent(AppEvent.DATA, null, false));
}else {
fileStream.addEventListener(Event.COMPLETE, fileReadCompleteHandler);
fileStream.openAsync(file, FileMode.READ);
fileStream.addEventListener(Event.CLOSE, fileClosedHandler);
fileStream.addEventListener(IOErrorEvent.IO_ERROR, IOErrorHandler);
}
private function fileReadCompleteHandler(event:Event):void {
var ob:Object;
var fileStream:FileStream = FileStream(event.currentTarget);
try {
ob.source = fileStream.readObject();
}catch (e:Error) {
trace('error:' + e.message)
}
fileStream.removeEventListener(Event.COMPLETE, fileReadCompleteHandler);
fileStream.close();
}
on fileReadCompleteHandler I get error: "Error #1009: Cannot access a property or method of a null object reference."
what I am missing, how can I read object from openAsync?
thanks
You never initialize object ob, of course accessing fields of a null object gives you #1009:
var ob:Object;
var fileStream:FileStream = FileStream(event.currentTarget);
try {
ob.source = fileStream.readObject();
You need to:
var ob:Object = new Object;
var fileStream:FileStream = FileStream(event.currentTarget);
try {
ob.source = fileStream.readObject();

Entity Framework fails to update records

I am developing a Webapp using MVC and Entity framework and i have encountered a problem which is starting to get pretty annoying now.
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(true)]
public ActionResult ChangeUser(HttpPostedFileBase avatar, int? id)
{
try
{
if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
if (ModelState.IsValid)
{
Models.Users usr = db.Users.Find(id);
var at = db.Users.Attach(usr);
if (usr == null) return HttpNotFound();
at.Password = Encryption.Encode(usr.Password);
at.Email = usr.Email;
at.NickName = usr.NickName;
if (avatar != null && avatar.ContentLength > 0)
{
var _fileName = Path.GetFileName(avatar.FileName);
var ext = Path.GetExtension(_fileName);
var fileName = Encryption.EncodeFileName(_fileName);
//End of file properties
var path = Path.Combine(Server.MapPath("~/CMS-Content/User/Files/Avatars/"), fileName + ext);
avatar.SaveAs(Server.MapPath(path));
at.ThumbnailPath = path;
}
db.Entry(usr).State = EntityState.Modified;
// other changed properties
db.SaveChanges();
TempData["result"] = "User settings changed successfully.";
}
}
catch
{
TempData["result"] = "An error occured to change the user information!";
}
return RedirectToAction("Users");
}
The problem is that the records in the database does not update. I get the output that they have been updated successfully but in database the records does not change.