How to display the response from an HTTPHandler on the cshtml page - c#

I have a cshtml page that has a form which sends data to an HTTPHandler. If I run into some kind of error I want to respond with an error message and display it in the same cshtml page. How can I do this?
Here is my handler
public void ProcessRequest(HttpContext context)
{
var mode = context.Request.Form["mode"];
var title = context.Request.Form["postTitle"];
var content = context.Request.Form["postContent"];
var slug = context.Request.Form["postSlug"];
var id = context.Request.Form["postId"];
var datePublished = context.Request.Form["postDatePublished"];
if (string.IsNullOrWhiteSpace(slug))
{
slug = CreateSlug(title);
}
if (mode == "edit")
{
EditPost(Convert.ToInt32(id), title, content, slug, datePublished, 1);
}
else if (mode == "new")
{
CreatePost(title, content, slug, datePublished, 1);
}
context.Response.Redirect("~/admin/post/");
}
private static void CreatePost(string title, string content,
string slug, string datePublished, int authorId)
{
var result = PostRepository.Get(slug);
DateTime? published = null;
if (result != null)
{
throw new HttpException(409, "Slug is already in use.");
}
if (!string.IsNullOrWhiteSpace(datePublished))
{
published = DateTime.Parse(datePublished);
}
PostRepository.Add(title, content, slug, published, authorId);
}
private static void EditPost(int id, string title, string content,
string slug, string datePublished, int authorId)
{
var result = PostRepository.Get(id);
DateTime? published = null;
if (result == null)
{
throw new HttpException(404, "Post does not exist.");
}
if (!string.IsNullOrWhiteSpace(datePublished))
{
published = DateTime.Parse(datePublished);
}
PostRepository.Edit(id, title, content, slug, published, authorId);
}
private static string CreateSlug(string title)
{
title = title.ToLowerInvariant().Replace(" ", "-");
title = Regex.Replace(title, #"[^0-9a-z-]", string.Empty);
return title;
}
And here is the form in the cshtml file
var post = Post.Current;
<div>
<form name="post" method="post" action="~/admin/post.ashx">
<input type="hidden" name="mode" value="#mode" />
<input type="hidden" name="postId" value="#post.Id" />
<p>Title: <input type="text" name="postTitle" value="#post.Title" /></p>
<p>Content: <textarea name="postContent">#post.Content</textarea></p>
<p>Slug: <input type="text" name="postSlug" value="#post.Slug" /></p>
<p>Date Published: <input type="text" name="postDatePublished" value="#post.DatePublished" /></p>
<p><input type="submit" name="postSubmit" value="Submit" /></p>
</form>
</div>
For example: Right now I'm throwing an exception if the post slug already exists. How would I send an error message that says "Slug is already in use" and then display it on the cshtml page preferably right on top of the form? Thanks.

Related

access input value in webAPI from post

I use the following code to upload files using a webAPI, the file upload part works fine but how can I access all additional input values and hidden input values from the post?
[HttpPost]
public async Task<object> UploadFile()
{
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
var streamProvider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/App_Data/Temp/"));
try
{
await Request.Content.ReadAsMultipartAsync(streamProvider);
foreach (MultipartFileData fileData in streamProvider.FileData)
{
var fileName = "";
if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
{
fileName = Guid.NewGuid().ToString();
}
fileName = fileData.Headers.ContentDisposition.FileName;
if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
{
fileName = fileName.Trim('"');
}
if (fileName.Contains(#"/") || fileName.Contains(#"\"))
{
fileName = Path.GetFileName(fileName);
}
File.Move(fileData.LocalFileName, Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/"), Path.GetDirectoryName(fileName) + Guid.NewGuid() + Path.GetExtension(fileName)));
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
And here is the form I am using for posting the file.
<form name="form1" method="post" enctype="multipart/form-data" action="api/upload">
<div>
<label for="caption">Image Caption</label>
<input name="caption" type="text" />
</div>
<div>
<input type="hidden" value="secretvalue"/>
<label for="image1">Image File</label>
<input name="image1" type="file" />
</div>
<div>
<input type="submit" value="Submit" />
</div>

MVC File is not being Posted back

HTTPPostedFileBase is always null in the controller. Please review and let me know where am I wrong.
Controller Post method
public ActionResult EditProfile(Contact model, HttpPostedFileBase picture, string currentPassword, string CurrentPasswordQ, string newPassword, string loginPwd, string currentPinQ, string newPin, int? selectedQuestion, string answer, bool pwdChange = false, bool questionChange = false, bool pinChange = false)
{
My Form Header
#using (Html.BeginForm("EditProfile", "CompanyAdmin", FormMethod.Post, new { enctype = "multipart/form-data", #data_ajax = "false" }))
{
And my file Input
<tr>
<td class="label_form_div">
<label>Profile Picture</label>
</td>
<td>
<input type="file" name="picture" />
</td>
</tr>
Please review and see if you can find what is wrong with this.
Thanks
Its seems your code is correct, anyway try this way in the controller. It might helpful for you:
public ActionResult EditProfile(Contact model, string currentPassword, string CurrentPasswordQ, string newPassword, string loginPwd, string currentPinQ, string newPin, int? selectedQuestion, string answer, bool pwdChange = false, bool questionChange = false, bool pinChange = false)
{
if (Request.Files != null && Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
//other logic
}
}
}
Source: https://stackoverflow.com/a/32219011/3397630
Please follow the below steps.
Step :- 1
#using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
}
Step :- 2
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(
Server.MapPath("~/images/profile"), pic);
// file is uploaded
file.SaveAs(path);
// save the image path path to the database or you can send image
// directly to database
// in-case if you want to store byte[] ie. for DB
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
}
// after successfully uploading redirect the user
return RedirectToAction("actionname", "controller name");
}

File is not uploading in ASP.Net MVC

Hi to all of you I am facing a problem on uploading a file and saving it into a folder here is my view
<div class="admin-empty-dashboard">
#using (Html.BeginForm("UploadResumes", "Employee", new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="icon">
<i class="ion-ios-book-outline"></i>
</div>
<h4>Welcome #Model.FullName!</h4>
<p>#ViewBag.Error</p>
<div class="form-group bootstrap-fileinput-style-01">
<label>Upload Resume</label>
<input type="file" name="file" required="required" class="btn btn-primary" style="margin-left:265px" accept="application/msword,text/plain, application/pdf">
<span class="font12 font-italic">** File must not bigger than 2MB</span>
</div>
<input type="submit" name="name" class="btn btn-primary" value="UploadResumes" />
}
</div>
and here is my controllers action problem is that it HttpPostedFileBase object value is always null and i ran Request.Files.Count it's also giving me zero where is problem?
public ActionResult UploadResumes(HttpPostedFileBase file)
{
if (Session["UserID"] != null && Session["UserName"] != null && Session["EmployeeID"] != null)
{
int id = Convert.ToInt32(Session["EmployeeID"]);
string[] allowedExtenssions = new string[] { ".pdf", ".doc", ".docx" };
string cvPath = "~/cvs/Employee_cvs/";
if (!Directory.Exists(Server.MapPath(cvPath)))
Directory.CreateDirectory(Server.MapPath(cvPath));
MyDbContext db=new MyDbContext();
tblEmployee employee = (from s in db.tblEmployees where s.UserId == id select s).FirstOrDefault();
// HttpPostedFileBase cv = Request.Files["CV"];
if (file != null)
{
if (file.ContentLength > 0)
{
string ext = Path.GetExtension(file.FileName);
if (allowedExtenssions.Contains(ext.ToLower()))
{
string fileName = DateTime.Now.Ticks + ext;
string filePath = cvPath + fileName;
string serverPath = Server.MapPath(filePath);
file.SaveAs(serverPath);
employee.cvUrl = filePath;
}
}
ViewBag.Error = "Some Error Occured";
}
return RedirectToAction("Dashboard");
}
else
{
return RedirectToAction("Login", "User");
}
}
Update like below and check
#using (Html.BeginForm("UploadResumes", "Employee",FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}
Also
[HttpPost]
public ActionResult UploadResumes(HttpPostedFileBase file)
{
}
Try changing your parameters on your controller to
public ActionResult UploadResumes(Model yourModel, HttpHostedFileBase file)
In most of my controllers that require a file for upload, are usually array based. Make you function parameters an array like this:
public ActionResult UploadResumes(HttpPostedFileBase[] files){
}

Asp.NET MVC 4 Ajax Request Cancels on Submit

Issue Is with Ajax Request Cancel
After i call the ProcessMessage from form submit i am having issue
Issue with submitting your page is canceling my ajax request, so I am getting error..
Please help me on this
View
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "formUpload", enctype = "multipart/form-data" }))
{
<div>
<b>Upload File</b>
<input type="file" name="file" />
<input type="submit" value="Upload File" name="btnUpload" onclick="progressStatus();"/><br />
</div>
<div>
#ViewBag.Message
</div>
<div style="width: 30%; margin: 0 auto;">
<div id="progressbar" style="width: 300px; height: 15px"></div>
<br/>
</div>
}
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
function progressStatus() {
var oReq = new XMLHttpRequest();
oReq.open("get", "/Home/ProcessMessage", true);
oReq.send();
setInterval(showResult, 1000);
function showResult() {
var result = "";
if (result !== oReq.responseText) {
result = oReq.responseText;
debugger;
$("#progressbar").html(result);
}
}
return false;
}
</script>
Controller
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null)
{
var fname = Path.GetFileName(file.FileName);
var exis = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Storage/uploads"), fname);
if (System.IO.File.Exists(exis))
{
ViewData["Message"] = "The file " + fname + " has already exists";
}
else
{
try
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var folderPath = Server.MapPath("~/Storage/uploads");
fname = fileName;
var path = Path.Combine(folderPath, fileName);
var filebytes = new byte[file.ContentLength];
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
file.SaveAs(path);
}
ViewData["Message"] = "The file " + fname + " has uploaded successully";
}
catch (Exception e)
{
ViewData["Message"] = "The file " + fname + " Could not upload";
ViewData["Message"] = e.Message;
}
}
}
else
ViewData["Message"] = "Please choose file";
return View();
}
public class ProgressiveResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
for (int i = 0; i < 20; i++)
{
context.HttpContext.Response.Write(i.ToString());
Thread.Sleep(2000);
context.HttpContext.Response.Flush();
}
context.HttpContext.Response.End();
}
}
and this is an action that returns this result:
public ActionResult ProcessMessage()
{
return new ProgressiveResult();
}
You have to return false in click event handler to cancel submitting the form:
<input type="submit" value="Upload File" name="btnUpload" onclick="progressStatus(); return false;"/>

How to show images on an HTML page

I am developing a ASP.NET MVC 4 web api to show product image associated with a company. In the database I have stored CompanyID & CompanyProductImageURL or CompanyProductImageFilepath. Now using my web api, when I click on 'Show Image' button, I want to show the product image on the same page. Right now, the url is localhost:1111/ViewCompanyProductImage.html ; when I enter CompanyID =31 & click on 'Show Image' button new tab opens with url http://localhost:1111/api/Images/?CompanyID=31 and then the CompanyProductImageURL or CompanyProductImageFilepath associated with that Company opens in another tab. I want the image to show up in localhost:1111/ViewCompanyProductImage.html under the 'SHow Image' button. Here's the code I have.
webapiconfig.cs
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ImagesApi",
routeTemplate: "api/Images/{companyid}"
defaults: new { Controller = "Images", companyid = #"\d+" }
);}
----Controller
public class ImagesController : ApiController
{
private static T ConvertFromDBVal<T>(object obj)
{
if (obj == null || obj == DBNull.Value)
{
return default(T); // returns the default value for the type
}
else
{
return (T)obj;
}
}
[System.Web.Http.AcceptVerbs("GET")]
public HttpResponseMessage Get(int companyid)
{
Images oldImages = new Images();
string sql = "select companyid,companyproducturl from [dbo].[CompanyImage] WHERE companyid = #companyid";
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["connection"].ConnectionString))
{
using (SqlCommand query = new SqlCommand(sql, connection))
{
SqlDataReader rdr;
query.Parameters.Add(new SqlParameter("#companyid", companyid));
query.CommandType = CommandType.Text;
connection.Open();
query.CommandTimeout = 90;
rdr = query.ExecuteReader();
if (rdr != null)
{
while (rdr.Read())
{
oldImages.companyid = ConvertFromDBVal<int>(rdr["companyid"]);
oldImages.companyproducturl = ConvertFromDBVal<string>(rdr["companyproducturl"]);
}
}
}
}
if (oldImages.companyid == 0 )
{
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, String.Format("No records found for companyid: {0} ", companyid)));
}
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
System.Diagnostics.Process.Start(oldImages.imageproducturl);
return response;
}
---view
public class Images
{
[Required(AllowEmptyStrings = false, ErrorMessage = "companyid Required")]
[Range(1, 10000)]
public int companyid { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "imageproducturl Required")]
public string companyproducturl { get; set; }
}
--index.cshtml
<div id="body">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1> Web API!</h1>
</hgroup>
</div>
</section>
<section class="content-wrapper main-content clear-fix">
<p>
For API documentation: #Html.ActionLink("API", "Index", "Help", new { area = "" }, null)
</p>
<p>
View Company Images:Click Here!
</p>
</section>
</div>
--ViewCompanyProductImage.html
<div class="jumbotron" align="center">
<h1>Images Web API</h1>
<p class="lead"></p>
</div>
<div class="row">
<div class="col-md-4" align="center">
<div class="first" align="center">
<form action="api/Images/" method="get" target="_blank">
companyid:
<br />
<input type="text" name="companyid"><br>
<td>
<input type="submit" value="Show Image" />
</form>
</div>
</div>
</div>
How can I show product image on the localhost:1111/ViewCompanyProductImage.html itself?
Thanks
R
You can do this using JavaScript.
Place an image element on the page, give it an ID and on button click, instead of submit, find the image element and set its src property to the desired URL.
<img src="" id="companyImage" />
<input type="text" name="companyid" />
<input type="button" value="Show Image" onclick="previewImage" />
And then in JS:
function previewImage() {
var companyId = getElementById('companyid').value;
getElementById('companyImage').src = "api/Images/?companyID=" + companyId;
}

Categories

Resources