Cancel button on MVC - asp.net-mvc

When the client click on Cancel (on ItemsOptions) he should go back to the previous page (Client):
I added in the View ItemsOptions:
#using (Html.BeginForm("","", FormMethod.Post, new { #class = "form-group", role = "form" }))
{
<div class="col-md-4"><input id = "theCancel" class="cancel" type="submit" value="Cancel" /></div>
}
When the Button Cancel is hit the error Message :
The required anti-forgery form field "__RequestVerificationToken" is not present.
I added in the controller
[ValidateAntiForgeryToken]
public ActionResult ***Client***(OrderItems model)
{
}
and in the Client View
#using (Html.BeginForm("Client", "Home", FormMethod.Post, new { #class = "form-group", role = "form" }))
{
#Html.AntiForgeryToken();
}
I tried another way:
I added in the View ItemsOptions:
#using (Html.BeginForm("","", FormMethod.Post, new { #class = "form-group", role = "form" }))
{
<div class="col-md-4"><input class="btn btn-warning" type="submit" value="Cancel" name="action:Cancel" /></div>
}
the controller
[MultipleButton(Name = "action", Argument = "Cancel")]
public ActionResult Cancel(OrderItems model)
{
return View("Client", model);
}
How can I implement the cancel button in the MVC form,I want the user to go to the previous page.
Thanks

If you just want the cancel button to go back
<script type='text/javascript'>
function goBack() {
window.history.back();
}
</script>
<!--cancel button-->
<button onclick='goBack()'>Cancel</button>
Does something like this work for you?

Related

I can't send a POST request from view to Controller in ASP.NET MVC

I have this form shown below:
#using (Html.BeginForm("NewArticle", "News",FormMethod.Post, new { name = "createForm", onsubmit = "return validateFormNewPost()" }))
{
#Html.TextBoxFor(p => p.adName, new { #class="form-control"})
#Html.DropDownListFor(p => p.tyepId, listType, "---Select Type---", new { #class = "form-control" })
#Html.TextBox("imgPath", "", new { #class = "form-control", id = "imgPath" })
#Html.TextAreaFor(p =>p.AdDescription,new { id = "editor" })
<button class="btn btn-reset btn-dark" type="reset">Reset</button>
<button class="btn-submit btn-primary btn" type="submit">Submit</button>
}
Controller:
[HttpGet]
public ActionResult NewArticle()
{
List<AdType> listType = typeModel.listForAdd();
SelectList s = new SelectList(listType, "id", "AdType1");
ViewBag.ListType = s;
return View();
}
[HttpPost]
public ActionResult NewArticle(Advertisement model,string imgPath)
{
// my code
return RedirectToAction("Category","News");
}
I'm trying to make a POST request by submit the form but it always send form data with a GET request. How can I fix it?
How are you sending the POST? Are you using AJAX or JavaScript from your MVC page or are you trying to hit the endpoint with an external application like Telerik Fiddler or Postman?
You can not make a POST request directly from the browser using the URL, my assumption is that may be what you are doing.
#using (Html.BeginForm("MethodNameinController", "Controller Name", FormMethod.Post))
{
//form fields with submit button
<input type="submit" value="Save" class="btn btn-default" id="create" />
}
And in Controller
[HttpPost]
public ActionResult MethodNameinController(Model model)
{
}

MVC Bootstrap modal show validation result

The problem:
I want to preform submit to form that is in modal and if validation faild to get the error message on the modal.
I'm using ajax validation (jQuery) as detailed here
Is there an elegant way to perform submit but on faild stay at modal to show error message?
My code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Cam c)
{
ViewBag.id = c.id;
using (Entities db = new Entities())
{
if (ModelState.IsValid)
{
db.camp.Add(c);
db.SaveChanges();
return RedirectToAction("Index", new { id = c.id });
}
}
return null;
}
Client:
#using (Html.BeginForm("Create", "Camp", FormMethod.Post, new { model =
Model }))
{
#Html.AntiForgeryToken()
<dt>
name:
</dt>
<dd>
#Html.TextBoxFor(model => model.name, new { #class = "form-control", #placeholder = "name", #id = "txtVenueID", style = "width:150px" })
</dd>
<dd>
#Html.ValidationMessageFor(model => model.name)
</dd>
<div class="modal-footer ">
<button type="button" class="btn btn-default" data-
dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
}
Model:
public partial class Cam
{
[Display(Name = "Name")]
[Required(ErrorMessage = "Require {0}")]
string name { get; set; }
}
Show the first form in modal via the action that build it but keep the model state errors - use This
For view to submit the form but keep result on the modal use the following:
<button type="submit" class="btn btn-primary">Save</button>
Javascript to get the submit result into the modal:
$(function () {
$.ajaxSetup({ cache: false });
$(':submit[data-modal]').on("click", function (e) {
e.preventDefault();
var linkObj = $(this).closest('form');
$.ajax({ // create an AJAX call...
data: linkObj.serialize(), // get the form data
type: linkObj.attr('method'), // GET or POST
url: linkObj.attr('action'), // the file to call
success: function(response) { // on success..
$('#Modal-Content').html(response); // update the DIV
}
});
});
});

Ajax.BeginForm return PartialView code does not update

I am doing a login logout functionality using Ajax partial. For this I have a View which checks if the user is logged in or not and shows login or logout form accordingly.
On submit it does a ajax request and logs in or out the user. after doing so in controller I return same partial view.
So expected behavior is on return partial view must again check for login status and refresh the view accordingly, but instead same form is loaded.
Partial View:
#model Models.LoginModel
#if (Member.MemberIsLoggedOn())
{
using (Ajax.BeginForm("LoginForm", "Account", null, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "login-form-update",
},new {
#class="loginform form"
}))
{
<div class="col-md-12 padding-zero">
<div class="row flt-right">
Hello #Context.User.Identity.Name, <input type="submit" name="logout" class="btn btn-default" value="Log Out" />
</div>
</div>
}
}
else
{
using (Ajax.BeginForm("LoginForm", "Account", null, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "login-form-update",
}, new {
#class = "loginform form"
}))
{
<div class="col-md-12 padding-zero">
<div class="row flt-right">
<div class="form-group col-md-5">
#Html.TextBoxFor(x => Model.Username, new { #class = "form-control", #placeholder = "Username" })
</div>
<div class="form-group col-md-5">
#Html.TextBoxFor(x => Model.Password, new { #class = "form-control", #placeholder = "Password", #type = "Password" })
</div>
<div class="form-group col-md-2 flt-right">
<input type="submit" name="login" class="btn btn-default" value="Go" />
</div>
</div>
</div>
}
}
Controller:
public class AccountController : Controller
{
[HttpPost]
public ActionResult LoginForm(LoginModel model)
{
if (!ModelState.IsValid)
{
//Do nothing
}
// Login
if (Membership.ValidateUser(model.Username, model.Password))
{
FormsAuthentication.SetAuthCookie(model.Username, false);
return PartialView("Header/LoginForm", new Models.LoginModel());
}
else
{
ModelState.AddModelError("Username", "Username is not valid");
//do nothing
}
}
public ActionResult Logout()
{
FormsAuthentication.SignOut();
Session.Clear();
return PartialView("Header/LoginForm", new Models.LoginModel());
}
}
Now my problem is login/logout happens properly, but changes do not reflect unless page is refreshed, which is i want to avoid by Ajax.BeginForm(),
update
If i click two times the view changes, but this is not a good user experience.
I think this might be due to cache problem. You need to use output cache attribute to disable the cache for that action method .
You can use something like this.
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
Also clear your ModelState before the return .
ModelState.Clear();
return PartialView(model);

How to display a model state error in case I am returning a partial view

I have the following action method for creating new network info:-
public ActionResult CreateVMNetwork(int vmid)
{
VMAssignIps vmips = new VMAssignIps()
{
TechnologyIP = new TechnologyIP() { TechnologyID = vmid},
IsTMSIPUnique = true,
IsTMSMACUnique = true
};
return PartialView("_CreateVMNetwork",vmips);
}
[HttpPost]
public ActionResult CreateVMNetwork(VMAssignIps vmip)
{
if (ModelState.IsValid)
{
try
{
repository.InsertOrUpdateVMIPs(vmip.TechnologyIP,User.Identity.Name);
repository.Save();
return PartialView("_networkrow",vmip);
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Error occurred: " + ex.InnerException.Message);
}
}
return PartialView("_CreateVMNetwork", vmip);
}
And I have the following _CreateVMNetwork view:-
#model TMS.ViewModels.VMAssignIps
#using (Ajax.BeginForm("CreateVMNetwork", "VirtualMachine", new AjaxOptions
{
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "networktable",
LoadingElementId = "loadingimag",
HttpMethod= "POST"
}))
{
#Html.ValidationSummary(true)
#Html.HiddenFor(model=>model.TechnologyIP.TechnologyID)
#Html.Partial("_CreateOrEditVMNetwork", Model)
<input type="submit" value="Save" class="btn btn-primary"/>
}
and _CreateOrEditVMNetwork view:-
#model TMS.ViewModels.VMAssignIps
<div>
<span class="f">IP Address</span>
#Html.EditorFor(model => model.TechnologyIP.IPAddress)
#Html.ValidationMessageFor(model => model.TechnologyIP.IPAddress)
<input type="CheckBox" name="IsTMSIPUnique" value="true" #(Html.Raw(Model.IsTMSMACUnique ? "checked=\"checked\"" : "")) /> |
<span class="f"> MAC Address</span>
#Html.EditorFor(model => model.TechnologyIP.MACAddress)
#Html.ValidationMessageFor(model => model.TechnologyIP.MACAddress)
<input type="CheckBox" name="IsTMSMACUnique" value="true" #(Html.Raw(Model.IsTMSMACUnique ? "checked=\"checked\"" : "")) />
</div>
The problem I am facing is that in case there is a model state error when adding a new entity, a partial view will be displayed with the model state error as follow:-
So my question is , if there is a way to display the model state error with the partial view , without updating the table row “insert after” as I am doing currently?
Thanks
Given the age i'm guessing you have already found a solution to this,
But here is an example using InsertionMode.Replace, maybe it can help someone else.
Snipped from view
#using (Ajax.BeginForm("AddPerson", "Home", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "UpdateSection" }))
{
<div id="UpdateSection">
#Html.Partial("PersonModel", Model.Person)
</div>
<input type="submit" value="add" />
}
Snipped from the controller
if (!ModelState.IsValid)
{
return PartialView("AddPerson", Person);
}
just make sure the "jquery.unobtrusive-ajax.min.js" script is included (i'm not sure it is by default)

MVC How to change a buttons text on submit

I'm trying to create a simple MVC 4 app with a few buttons that when clicked adds one to their text value. The problem is when I use < input > buttons I can't change the text value when I submit the form and when I use < button > then there is nothing passed to the action.
I have a simple SQL Database that the controller hits which is where the initial ViewData values are coming from and how it's storing the buttons current value.
Also I'm currently trying to do this with multiple forms but if it is possible with one form then that would be ideal.
#using (Ajax.BeginForm("AddOne", "Home", null, new AjaxOptions { UpdateTargetId = "btn-tc-top"}, new { #class = "rectangle-top" }))
{
<input type="submit" class="button" name="button" id="btn-tc-top" value="#ViewData["ct-t"]"/>
}
#using (Ajax.BeginForm("AddOne", "Home", null, new AjaxOptions { UpdateTargetId = "btn-tc-bottom"}, new { #class = "rectangle-bottom" }))
{
<button type="submit" class="button" name="button" id="btn-tc-bottom">#ViewData["ct-b"]</button>
}
You could subscribe to the OnSuccess handler:
#using (Ajax.BeginForm("AddOne", "Home", new { id = "btn-tc-top" }, new AjaxOptions { OnSuccess = "addSuccess" }, new { #class = "rectangle-top" }))
{
<input id="btn-tc-top" class="button" type="submit" name="button" value="#ViewData["ct-t"]" />
}
#using (Ajax.BeginForm("AddOne", "Home", new { id = "btn-tc-bottom" }, new AjaxOptions { OnSuccess = "addSuccess" }, new { #class = "rectangle-bottom" }))
{
<input id="btn-tc-bottom" class="button" type="submit" name="button" value="#ViewData["ct-b"]" />
}
which could be defined like this:
function addSuccess(result) {
$('#' + result.id).val(result.text);
}
and the controller:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["ct-t"] = "1";
ViewData["ct-b"] = "2";
return View();
}
[HttpPost]
public ActionResult AddOne(string id, int button)
{
return Json(new { id = id, text = button + 1 });
}
}

Resources