I received error saying:
HTTP 404. The resource you are looking for (or one of its
dependencies) could have been removed, had its name changed, or is
temporarily unavailable. Please review the following URL and make
sure that it is spelled correctly. Requested URL:
/PCController/Progress
PCController is my controller's name.
This is from my controller:
[HttpGet]
public ActionResult Progress()
{
return View();
}
[HttpPost]
public ActionResult Progress(HttpPostedFile file)
{
try
{
if (file.ContentLength > 0)
{
string _FileName = Path.GetFileName(file.FileName);
string _path = Path.Combine(Server.MapPath("~/Content/PC"), _FileName);
file.SaveAs(_path);
}
ViewBag.Message = "File Uploaded Successfully!!";
return View();
}
catch
{
ViewBag.Message = "File upload failed!!";
return View();
}
}
And this one is for my View:
#using (Html.BeginForm("Progress", "PCController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
#Html.TextBox("file", "", new { type = "file" }) <br />
<input type="submit" value="Upload" />
#ViewBag.Message
</div>
}
I shouldnt put Controller there, should be "PC" instead.
#using (Html.BeginForm("Progress", "PC", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBox("file", "", new { type = "file" })
<input type="submit" value="Upload" />
#ViewBag.Message
</div>
}
Related
When I click submit, the page is refreshed and looks like everything went through, but is not hitting the ActionResult I am trying to send it to.
I've tried submitting normally and with JavaScript and neither will work.
<form method="post" autocomplete="off" asp-controller="Default" asp-action="Submit">
<button id="SubmitButton" type="submit">Submit</button>
</form>
Controller Method:
namespace (Removed).Controllers
{
public class DefaultController : Controller
{
[HttpPost]
public ActionResult Submit()
{
DBController1 DB1 = new DBController1();
AlertManagement am = new AlertManagement();
am.FirstName = Request.Form["FirstName"];
am.LastName = Request.Form["LastName"];
am.Email = Request.Form["EmailAddress"];
am.Mobile = Request.Form["PhoneNumber"].Replace("(", "").Replace(")", "").Replace(" ", "").Replace("-", "");
am.Affiliation = Request.Form["Affiliation"];
am.StartDate = Convert.ToDateTime(Request.Form["StartDate"]).Date;
am.EndDate = Convert.ToDateTime(Request.Form["EndDate"]).Date;
DB1.AlertManagement.Add(am);
DB1.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Index()
{
return View();
}
}
}
Here is the RouteConfig:
namespace (Removed)
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Index",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Submit",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Submit", id = UrlParameter.Optional }
);
}
}
}
When I click submit, it always goes to ActionResult Index()
Taking a shot in the dark here, but does your controller look like this?
public class DefaultController: Controller
{
[HttpPost] // This attribute states that this action result can only be accessed when using http POST verb.
public IActionResult Submit()
{
return RedirectToAction("index", "home");
}
}
Also, what are you posting? If you have intentionally left out the fields in your example make sure that in your POST method you have this.
<form method="post" autocomplete="off" asp-controller="Default" asp-action="Submit">
<input type="text" name="nameOfElement" id="clientName" />
<button id="SubmitButton" type="submit">Submit</button>
</form>
public class DefaultController: Controller
{
[HttpPost]
public IActionResult Submit([FromForm] string nameOfElement)
{
return RedirectToAction("index", "home");
}
}
try this
<form action="/Default/Submit" method="post">
<input type="submit">
</form>
the ActionMethod you are expecting to be called is of Verb 'GET' while your Form submit method type is 'POST'
add HttpPost attribute it shouls work
[HttpPost]
Public ActionResult Submit()
{
}
Login.cshtml
<script type="text/javascript">
function data() {
var n = document.getElementById("username").value;
var m = document.getElementById("password").value;
?
</script>
<button type="submit"class="btn-login" onClick="Data()">
Giriş Yap </button>
Account Controller
DBEntities dB = new DBEntities();
[HttpPost] (username) (password)
public ActionResult Login(string KullaniciAdi,string Sifre)
{
// Session[KullaniciAdi] = dB.Profil.Where(x => x.KullaniciAdi == KullaniciAdi && x.Sifre == Sifre).FirstOrDefault();
var session = (from p in dB.Profil
where p.KullaniciAdi == KullaniciAdi
select p).FirstOrDefault();
return View();
}
My OOP homework is this website and i want to create a login with sending password and username to controller and compare submitted data and the data in the database .Please help :)
You can send client data by using ajax request,
this is your inputs
<input id="username" type="text" />
<input id="password" type="password" />
<input id="loginbutton" onclick="UserLogin()" type="submit" value="Submit" />
Submit button bind with UserLogin js function.
here is the js function. we are sending ajax post request here to our controller
<script type="text/javascript">
function UserLogin() {
var n = document.getElementById("username").value;
var p = document.getElementById("password").value;
var postObj = JSON.stringify({
"username": n,
"password": p
});
$.ajax({
url: "/Home/Login", // endpoint
type: "POST",
data: postObj,
contentType: "application/json; charset=utf-8",
success: function (result) {
// success
},
error: function (errorData) { onError(errorData); }
});
}
</script>
And your controller should be like, you can implement login logic inside of the method.
[HttpPost]
public ActionResult Login(string username, string password)
{
// use your code loged in
return Json(true, JsonRequestBehavior.AllowGet);
}
First You Create a Class :
public class LoginModel
{
[Required(ErrorMessage = "User Name can not be empty!")]
public string LOGINID { get; set; }
[Required(ErrorMessage = "Password can not be empty!")]
public string LOGINPW { get; set; }
}
Then Your Controller Action Method do this:
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
//Here check the Login Id and Password
return View();
}
Now in view Write this. Now when you click the submit button a post call go to the Login Controller with given LOGINID and LOGINPW :
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<!-- login screen -->
<form action="#">
#Html.TextBoxFor(m => m.LOGINID, htmlAttributes: new { #class = "form-control", placeholder = "Login ID" })
#Html.ValidationMessageFor(model => model.LOGINID, "", new { #class = "text-danger", style = "float: left" })
#Html.PasswordFor(m => m.LOGINPW, htmlAttributes: new { #class = "form-control", placeholder = "Password" })
#Html.ValidationMessageFor(model => model.LOGINPW, "", new { #class = "text-danger", style = "float: left" })
<button type="submit" class="btn btn-primary" style="background: #2e6da4; color: #FFF;">Login</button>
</form>
}
#{
var actionURL = Url.Action("Action", "Controller",
FormMethod.Post, Request.Url.Scheme)
+ Request.Url.PathAndQuery;
}
#using (Html.BeginForm("Action", "Controller", FormMethod.Post,
new { #action = actionURL }))
{
<input type="text" name="username">
<input type="text" name="password">
<button type="submit"class="btn-login"></button>
}//Then use Request.Form[0] with the id to get the user name and password in the controller action.
When I am saving my data for the first time (when clicked on save button of my view) then I am getting value of submitButton variable in my controller action. But when I am editing my view and then click on save then I am getting null value in submitButton variable in my controller action.
My View Model
public class TermiViewModel : ViewModelBase
{
public long Id { get; set; }
public string Name { get; set; }
}
My View
#model TermiViewModel
#using (Html.BeginForm("MyActionMethod", "MyController", FormMethod.Post))
{
#Html.HiddenFor(model => model.Id)
<div>
#Html.LabelFor(model => model.Name)
#Html.EditorFor(model => model.Name)
</div>
<button name="submitButton" value="Save" type="submit"
onclick="return JavaScriptFunction();">Save</button>
<button name="submitButton" value="Cancel" type="submit"
onclick="return JavaScriptFunction();">Cancel</button>
}
Below is the Javascript I am using in my view.
<script language="javascript" type="text/javascript">
function JavaScriptFunction() {
return true;
}
</script>
Below is my Controller class.
public class MyController : CoreMvcController
{
private readonly ITermiRepositoryService _termiRepository;
public MyController(ITermiRepositoryService termiRepository)
{
_termiRepository = termiRepository;
}
}
Below is my action Method where I am getting values from my view.
[HttpPost]
public ActionResult MyActionMethod(TermiViewModel termiViewModel, string submitButton)
{
try
{
voucherViewModel =_termiRepository.Save(termiViewModel);
switch (submitButton)
{
case "Cancel":
return RedirectToAction("Edit",termiViewModel.Id);
default:
return RedirectToAction("Index");
}
}
catch (Exception exception)
{
}
return RedirectToAction("Index");
}
In my above Controller method I get the null value for my submitButton variable while editing my view. I don't understand why I am getting null value because while creating for the first time, I am getting values of submitButton from the submit button.
Thanks for any help!
For the solution, I need to change following classes:
My View Model:
// A new property "SaveButtonValue" added to my view model.
public class TermiViewModel : ViewModelBase
{
public long Id { get; set; }
public string Name { get; set; }
public string SaveButtonValue { get; set; }
}
My View:
// Added a hidden field for "SaveButtonValue" and passing this keyword in
// Javascript function for onclick of submit button.
#model TermiViewModel
#using (Html.BeginForm("MyActionMethod", "MyController", FormMethod.Post))
{
#Html.HiddenFor(model => model.Id)
#Html.HiddenFor(model => model.SaveButtonValue)
<div>
#Html.LabelFor(model => model.Name)
#Html.EditorFor(model => model.Name)
</div>
<button name="submitButton" value="Save" type="submit"
onclick="return JavaScriptFunction(this);">Save</button>
<button name="submitButton" value="Cancel" type="submit"
onclick="return JavaScriptFunction(this);">Cancel</button>
}
Javascript:
// Populating my property "SaveButtonValue" through javascript
<script language="javascript" type="text/javascript">
function JavaScriptFunction(submitButton)
{
if (objButton) {
$('#SaveButtonValue').val(submitButton.value);
}
return true;
}
</script>
My action method:
[HttpPost]
public ActionResult MyActionMethod(TermiViewModel termiViewModel)
{
try
{
voucherViewModel =_termiRepository.Save(termiViewModel);
switch (termiViewModel.SaveButtonValue)
{
case "Cancel":
return RedirectToAction("Edit",termiViewModel.Id);
default:
return RedirectToAction("Index");
}
}
catch (Exception exception)
{
}
return RedirectToAction("Index");
}
I am using an ajax.beginform to create a partial view within another view.
I the user enters a correct sn everything works fine.
But if the user enters an invalid number, I want to redirect to the index view.
Now the index page is submitted as a partial view in itself.
How can I avoid that.
Here is a part of my view and 2 simplified actionresults.
#using (Ajax.BeginForm("MachineInfo", "QrCreate", new AjaxOptions() {
HttpMethod = "POST", UpdateTargetId = "form-content", InsertionMode =
InsertionMode.ReplaceWith }))
{
#Html.AntiForgeryToken()
<input type="text" id="sn" name="sn" class="inputsn"
placeholder="Enter your serial number here..." />
<input type="submit" value="Search" class="search btn btn-success btn-lg" />
}
</div>
</div>
<div id="form-content"></div>
my Controller
public ActionResult Index(bool? isValidMachine = null)
{
ViewBag.invalidSerialNumber = isValidMachine;
return View();
}
[HttpPost]
public ActionResult MachineInfo(string sn)
{
if(string.IsNullOrEmpty(sn))
RedirectToAction("Index", new { isValidMachine = false });
QrCreateViewModel qrCreateVM;
using (var machineService = new MachineApiService())
{
var machine = machineService.GetMachineFromSerialNumber(sn);
if (machine == null)
return RedirectToAction("Index", new { isValidMachine = false });
else
qrCreateVM = new QrCreateViewModel(machine, GetBasePath());
}
if (qrCreateVM.IsValid())
{
qrCreateVM.Viewurl = qrCreateVM.QrCreateUrlOrDefaultNull();
return PartialView(qrCreateVM);
}
else
return RedirectToAction("Index", new { isValidMachine = false });
}
Ajax calls do not redirect (the purpose of making them is to stay on the same page).
In your controller method, replace the instances of return RedirectToAction(...) to return a HttpStatusCodeResult indicating an error, which you can then handle in the OnFailure option to redirect to the Index() method.
For example
[HttpPost]
public ActionResult MachineInfo(string sn)
{
if (string.IsNullOrEmpty(sn))
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bad Request");
}
....
Then in the Ajax.BeginForm()
#using (Ajax.BeginForm("MachineInfo", "QrCreate", new AjaxOptions() {
HttpMethod = "POST",
UpdateTargetId = "form-content",
InsertionMode = InsertionMode.ReplaceWith,
OnFailure = "redirect"
}))
{
....
and add the following script to redirect
function redirect(ajaxContext) {
location.href = '#Url.Action("Index")';
}
I'm trying build an Asp.net web api for posting files. I found the following example in
https://code.msdn.microsoft.com/AngularJS-with-Web-API-22f62a6e
The Web API method is:
[RoutePrefix("api/photo")]
public class PhotoController : ApiController
{
private IPhotoManager photoManager;
public PhotoController()
: this(new LocalPhotoManager(HttpRuntime.AppDomainAppPath + #"\Album"))
{
}
public PhotoController(IPhotoManager photoManager)
{
this.photoManager = photoManager;
}
// GET: api/Photo
public async Task<IHttpActionResult> Get()
{
var results = await photoManager.Get();
return Ok(new { photos = results });
}
// POST: api/Photo
public async Task<IHttpActionResult> Post()
{
// Check if the request contains multipart/form-data.
if(!Request.Content.IsMimeMultipartContent("form-data"))
{
return BadRequest("Unsupported media type");
}
try
{
var photos = await photoManager.Add(Request);
return Ok(new { Message = "Photos uploaded ok", Photos = photos });
}
catch (Exception ex)
{
return BadRequest(ex.GetBaseException().Message);
}
}
And the file uploader html code: (I added a text input <input type="text" id="test" value="testit" /> for test.
<form name="newPhotosForm" role="form" enctype="multipart/form-data" ng-disabled="appStatus.busy || photoManagerStatus.uploading">
<div class="form-group" ng-hide="hasFiles">
<label for="newPhotos">select and upload new photos</label>
<input type="file" id="newPhotos" class="uploadFile" accept="image/*" eg-files="photos" has-files="hasFiles" multiple>
<input type="text" id="test" value="testit" /> <!--- Added a text input for test -->
</div>
<div class="form-group" ng-show="hasFiles && !photoManagerStatus.uploading">
<ul class="list-inline">
<li><strong>files:</strong></li>
<li ng-repeat="photo in photos"> {{photo.name}}</li>
</ul>
<input class="btn btn-primary" type="button" eg-upload="upload(photos)" value="upload">
<input class="btn btn-warning" type="reset" value="cancel" />
</div>
<div class="form-group" ng-show="photoManagerStatus.uploading">
<p class="help-block">uploading</p>
</div>
</form>
The JS upload function:
function upload(photos)
{
service.status.uploading = true;
appInfo.setInfo({ busy: true, message: "uploading photos" });
var formData = new FormData();
angular.forEach(photos, function (photo) {
formData.append(photo.name, photo);
});
return photoManagerClient.save(formData)
.$promise
.then(function (result) {
if (result && result.photos) {
result.photos.forEach(function (photo) {
if (!photoExists(photo.name)) {
service.photos.push(photo);
}
});
}
appInfo.setInfo({message: "photos uploaded successfully"});
return result.$promise;
},
function (result) {
appInfo.setInfo({message: "something went wrong: " + result.data.message});
return $q.reject(result);
})
['finally'](
function () {
appInfo.setInfo({ busy: false });
service.status.uploading = false;
});
}
However, it seems the value of the added input test cannot be passed to the Web API code?
You need to add custom DTO/POCO class, set the values and then pass it as parameter to your post method. Since file is not a simple type default MediaTypeFormatter of webAPI won't work so you need to build your custom MediaTypeFormatter.
Sample POCO class
Public Class Attachment
{
public string Input {get;set;}
public byte[] Content{get;set;}
}
Custom Media formatter as below
public class CustomFormatter : MediaTypeFormatter
{
/// <summary>
///
/// </summary>
public CustomFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
}
public override bool CanReadType(Type type)
{
return type == typeof(Attachment);
}
public override bool CanWriteType(Type type)
{
return false;
}
public async override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
var provider = await content.ReadAsMultipartAsync();
var modelContent = provider.Contents
.FirstOrDefault(c => c.Headers.ContentType.MediaType == "application/json");
var attachment = await modelContent.ReadAsAsync<Attachment>();
var fileContents = provider.Contents
.Where(c => c.Headers.ContentType.MediaType == "image/jpeg").FirstOrDefault(); // or whatever is the type of file to upload
attachment.Content = await fileContents.ReadAsByteArrayAsync();
return attachment;
}
}
Register the custom media formatter:
private void ConfigureWebApi(HttpConfiguration config)
{
//other code here
config.Formatters.Add(new CustomFormatter());
}
Pass the POCO to your Web-API Controller
public async Task<IHttpActionResult> Post(Attachment attachment)
{
I haven't tested this in Visual Studio, but this is the approach you need to follow
More information here:
http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters
And a sample here
http://blog.marcinbudny.com/2014/02/sending-binary-data-along-with-rest-api.html#.V5MDDzV7qYg