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()
{
}
Related
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>
}
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")';
}
Hi I am working with mvc4
I have a razor view page for the action
public ActionResult DeliveryAddress(string userid,int productid)
{
....
return View(m);
}
that contain
<div >DELIVER HERE</div>
when clicking on this i am collecting somedata ifrom this page using jquery,
$(document).ready(function () {
$("#place-order").click(function () {
var userid = $('#selected-userId').html();
var productid = $('#selected-productId').html();
$.get("Products/PlaceOrder/"+ userid, function (data) { });
});
});
and i want to pen another view of action
[HttpGet]
public ActionResult PlaceOrder(int uid)
{
return View();
}
and paste the variable content,
but $.get("Products/PlaceOrder", function (data) { }); is not hitting this action..
please help me.
This is how you need to pass a data to a url in Jquery get method, note the same parameter name is used in the function
$.get('#Url.Action("PlaceOrder","Products")', { uid: userid }, function (data)
{
});
Make sure your URL is correct. Most probably use #Url.Action(). and also pass the parameter using new as shown below.
$.get('#Url.Action("PlaceOrder","Products",new { userid = #userid , productid = #productid })', function (data) {
});
While collecting the data make sure your parameter names are same for both while sending and while receiving.
[HttpGet]
public ActionResult PlaceOrder(int userid, int productid )
{
return View();
}
Just add HTTPGET attribute in your action method as below.
[HttpGet]
public ActionResult PlaceOrder()
{
return View();
}
java script
$("#place-order").click(function () {
var userid = $('#selected-userId').html(); // $('#selected-userId').val();
$.get('#Url.Action("PlaceOrder","Products", new { uid = userid })', function (data) { });
var productid = $('#selected-productId').html();
});
When I want my view code to be fetched like that, or even through the Html.Action() call, I use the PartialView and normally set my Controller Action as:
public ActionResult PlaceOrder(int uid)
{
return PartialView(new TestViewModel() { ID = uid });
}
as an example:
TestViewModel
public class TestViewModel
{
public int ID { get; set; }
}
PlaceOrder.cshtml
#model TestViewModel
<h2>Partial View</h2>
<p>
Partial View paragraph with the id <b>#Model.ID</b>
</p>
Index.html
<hr />
#Html.Action("PartialView", "Home", new { id = 44 })
<hr />
<div class="ap"></div>
<script>
var url = '#Url.Action("PartialView", "Home")';
$.get(url, { id: 54 }, function (data) {
$(".ap").append(data);
});
</script>
result: