MVC4 C# multiple Forms one page validations - asp.net-mvc

I've got 3 forms on one view on mvc project like this"
VIEW:
<div>
<fieldset>
<legend>Deposit Money</legend>
<div>#Html.LabelFor(u=>u.AccountNumber1)</div>
<div>#Html.DropDownList("Accounts", "-- Select Account --")
</div>
<div>#Html.LabelFor(u=>u.Amount)</div>
<div>#Html.TextBoxFor(u => u.Amount,new {style = "width:150px"})
#Html.ValidationMessageFor(u => u.Amount)
</div>
<div>#Html.LabelFor(u=>u.Comment)</div>
<div>#Html.TextAreaFor(u => u.Comment,new {style = "width:250px"})
#Html.ValidationMessageFor(u => u.Comment)
</div>
<input type="submit" value ="Submit" />
<input type="reset" value ="Clear" />
</fieldset>
</div>
}
</div>
<div id="middlepanel" style="position:absolute;left:33%;right:33%;">
#using (Html.BeginForm("Withdrawal", "ATM", FormMethod.Post, new { }))
{
#Html.ValidationSummary(true,"Deposit Failed. Check Your Details");
<div>
<fieldset>
<legend>Withdraw Money</legend>
<div>#Html.LabelFor(u=>u.AccountNumber1)</div>
<div>#Html.DropDownList("Accounts", "-- Select Account --")
</div>
<div>#Html.LabelFor(u=>u.Amount)</div>
<div>#Html.TextBoxFor(u => u.Amount,new {style = "width:150px"})
#Html.ValidationMessageFor(u => u.Amount)
</div>
<div>#Html.LabelFor(u=>u.Comment)</div>
<div>#Html.TextAreaFor(u => u.Comment,new {style = "width:250px"})
#Html.ValidationMessageFor(u => u.Comment)
</div>
<input type="submit" value ="Submit" />
<input type="reset" value ="Clear" />
</fieldset>
</div>
}
</div>
<div id="rightpanel" style="position:absolute;right:0;width:33%;">
#using (Html.BeginForm("Transfer", "ATM", FormMethod.Post, new { }))
{
#Html.ValidationSummary(true,"Deposit Failed. Check Your Details");
<div>
<fieldset>
<legend>Transfer Money</legend>
<div>#Html.LabelFor(u=>u.AccountNumber1)</div>
<div>#Html.DropDownList("Accounts", "-- Select Account --")
</div>
<div>#Html.LabelFor(u=>u.AccountNumber2)</div>
<div>#Html.DropDownList("Accounts", "-- Select Account --")
</div>
<div>#Html.LabelFor(u=>u.Amount)</div>
<div>#Html.TextBoxFor(u => u.Amount,new {style = "width:150px"})
#Html.ValidationMessageFor(u => u.Amount)
</div>
<div>#Html.LabelFor(u=>u.Comment)</div>
<div>#Html.TextAreaFor(u => u.Comment,new {style = "width:250px"})
#Html.ValidationMessageFor(u => u.Comment)
</div>
<input type="submit" value ="Submit" />
<input type="reset" value ="Clear" />
</fieldset>
</div>
}
</div>
in my controller, I am processing each of the above functionality.
However when one of the forms have an error (i.e blank field)
error is displayed on all the forms (validationSummary)
how can I build invidual errors per form?

Consider using partial views for each forms and call your partial view in your main view using
#Html.Partial("PartialViewName")

Related

How to validate a duplicate post request from a form in MVC

I am having an form which insert a record whenever a post request is made,but the problem is that if someone clicks submit button more than 1 times than duplicate post request are made and at the end same records are getting inserted. I dont want to check that the record is already present or not because the record would be different always. I tried using ValidateAntiForgeryToken filter in controller but it is failing to validate the requests, Below is my View Code.
#using (Html.BeginForm("Create", "Home",FormMethod.Post,new { onkeydown = "return event.keyCode!=13" }))
{
#Html.AntiForgeryToken()
<div class="right-col">
#Html.TextBoxFor(model => model.Name, new { placeholder = "Name", #class = "small-box" })
</div>
<div class="left-col">Email Id :</div>
<div class="right-col">
#Html.TextBoxFor(model => model.EmailId, new { placeholder = "Email Id", #class = "small-box",id="resumeemailid" })
#Html.ValidationMessageFor(model => model.EmailId)
</div>
<div class="left-col">Address :</div>
<div class="right-col">
#Html.TextAreaFor(model => model.Address, new { placeholder = "Address", #class = "small-box" })
</div>
<div class="buttons resume-threebutton">
<input type="submit" id="register-button" class="gradient-btn" value="#T("Account.Passport.Register.Button.Upload", "Upload")" name="Command" />
<input type="submit" id="register-button" class="gradient-btn" value="#T("Account.Passport.Button.UploadandAdd", "Upload And Add New")" name="Command" />
<input type="button" id="register-button" class="gradient-btn" value="#T("Account.Passport.Register.Button.Cancel", "cancel")" name="register-button" onclick="location.href='#Url.Action("SelectTemplate", "CustomerTemplate")'" />
</div>
}
and below is my controller Post method
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ProductModel model)
{
//To do add the product here...
}

MVC Partial view to register button control action is Not applicable

I am use MVC Partial view .I have a two of Page AddPoll.cshtml and Listpoll.cshtml. page AddPoll.cshtml use Partial view.
I use AddPoll:partial view page to be placed a partial view with Listpoll.
#Html.Partial("/Areas/admin/Views/Poll/AddPoll.cshtml",new Mvc_baker.Areas.admin.Models.pollquestion());
AddPoll.cshtml
#model Mvc_baker.Areas.admin.Models.pollquestion
<link href="~/Content/bootstrapvalidform.css" rel="stylesheet" />
#using (Html.BeginForm(actionName: "AddPoll", controllerName: "Poll"))
{
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<form class="">
<div class="col-md-6">
<div class="panel panel-primary">
<label class="control-label">پرسش</label>
#Html.TextBoxFor(m => m.QuestionText, new { id = "Name",style="width:450px", #class = "form-control" })
#Html.ValidationMessageFor(m => m.QuestionText)
<input class="btn btn-primary btn-default" name="commit" value="register" type="submit">
</div>
</div>
</form>
}
When I click the register button control action is Not applicable
When the breakpoint action on control and I can not run
You seem to have 2 nested html forms which is invalid markup. The Html.BeginForm helper already generates a <form> tag. So you should get rid of the inner form.
#model Mvc_baker.Areas.admin.Models.pollquestion
<link href="~/Content/bootstrapvalidform.css" rel="stylesheet" />
#using (Html.BeginForm(actionName: "AddPoll", controllerName: "Poll"))
{
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="col-md-6">
<div class="panel panel-primary">
<label class="control-label">پرسش</label>
#Html.TextBoxFor(m => m.QuestionText, new { id = "Name",style="width:450px", #class = "form-control" })
#Html.ValidationMessageFor(m => m.QuestionText)
<input class="btn btn-primary btn-default" name="commit" value="register" type="submit" />
</div>
</div>
}

Why Http Get action is called instead of Http post action?

I'm working with MVC and spent whole day getting stuck with this problem. Here is code at the controller:
public class CMController : Controller
{
public ActionResult SignUp()
{
return View("SignUpPage");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SignUp(User u)
{
if (ModelState.IsValid)
{
using (CmdbEntities dc = new CmdbEntities())
{
dc.Users.Add(u);
dc.SaveChanges();
ModelState.Clear();
u = null;
ViewBag.Message = ("Successfully sign on");
}
}
else
{
ViewBag.Message = ("Error");
}
return View("Welcome");
}
}
Here is the SignUpPage.cshtml view:
#using (Html.BeginForm("SignUp", "CM", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-group" style="padding:5px 50px">
<label> First name:</label>
<div>
#Html.TextBoxFor(model => model.FirstName, new {#class="form-control", placeholder="Enter first name", ID="FirstName"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<label >Last name:</label>
<div>
#Html.TextBoxFor(model => model.LastName, new {#class="form-control", placeholder="Enter first name", ID="LastName"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<label for="email">Email:</label>
<div>
#Html.TextBoxFor(model => model.Email, new {#class="form-control", placeholder="Enter email", ID="Email", type="email"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<label >User name:</label>
<div>
#Html.TextBoxFor(model => model.UserName, new {#class="form-control", placeholder="Enter user name", ID="UserName"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<label for="pwd">Password:</label>
<div>
#Html.TextBoxFor(model => model.Password, new {#class="form-control", placeholder="Enter password", ID="Password", type="password"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<label for="pwd">Confirm password:</label>
<div>
#Html.TextBoxFor(model => model.ConfirmPassword, new {#class="form-control", placeholder="Re-enter password", ID="_password", type="password"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<div>
<input type="submit" ID="SignUp" class="btn btn-success" value="Sign Up" />
</div>
</div>
}
The problem is, when load page first time, the action SignUp() is called which is correct. But when submit the form, SignUp() is called again instead of the post action SignUp(User u).
One more problem, even the form has post method, when click submit the url contains input information just like get method, I don't understand.
Here is the page html source of form tag.
<form action="/CM/SignUp" method="post"><input name="__RequestVerificationToken" type="hidden" value="VJ0YcQr1Z-l3Qo717pRpZNT-QtL59G2EJXy2JQL8NFnOm-XoNnAD-8T-Itz3i1EboGj0bhpBf2G26ifxm4F5ZRyKimkOyZW1AxZ3ckPNuRk1" />
Please help, thank you.
Can you please try adding
[AllowAnonymous]
to the post method?
Did you activate global authorization anywhere
System.Web.Mvc.AuthorizeAttribute
?

Call action depending on what button was clicked within form

I have a log in/register form with a button for each function
<div id="ManualLogin">
#using (Html.BeginForm(new { Controller = "Companies", Action = "ManualLogOn" }))
{
<fieldset>
<legend>Enter details</legend>
<div class="editor-label">
#Html.LabelFor(u => u.Name)
</div>
<div class="editor-field">
#Html.TextBoxFor(u => u.Name)
</div>
<div class="editor-label">
#Html.LabelFor(u => u.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(u => u.Password)
</div>
<input type="submit" id="LogInButton" name="Command" value="Log in"/>
<input type="submit" id="RegisterButton" name="Command" value="Register"/>
<label id="ServerValidaiotnLabel">#ViewBag.Error</label>
</fieldset>
}
</div>
How can I change this to make it call an action depending on what button was clicked. (Log in / Register)
You can toggle form action on buttons click and submit form manually.
Here sample:
Changes in form markup:
<buttom id="LogInButton" data-action="#Url.Action("login", "user")" class="Command">Log in</button>
<button id="RegisterButton" data-action="#Url.Action("register", "user")" class="Command"></button>
jQuery:
<script type="text/javascript">
(function($){
$('form button.Command').on('click', function() {
var url = $(this).data('action');
$(this).closest('form').attr('action', url).submit();
});
})(jQuery)
</script>

MVC form multipart/form-data isnt rendering correctly

here is my view. I am attempting to have a file upload control.
#section termimalContent {
#using (Html.BeginForm("Add", "Terminals_Policies", "multipart/form-data"))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>
<h2>
Create new policy</h2>
</legend>
<p>
<strong>Assigning devices to Node:</strong> #Model.GroupName</p>
<div class="editor-label">
#Html.LabelFor(model => model.PolicyName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PolicyName)
#Html.ValidationMessageFor(model => model.PolicyName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PolicyType)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.SelectedItems, new SelectList(Model.PolicyType, "Value", "Text"))
#Html.ValidationMessageFor(model => model.SelectedItems)
</div>
<div class="editor-label">
<label for="file1">
Filename:</label>
</div>
<div class="editor-field">
<input type="file" name="files" id="file1" />
</div>
<div class="editor-label">
<label for="file2">
Filename:</label>
</div>
<div class="editor-field">
<input type="file" name="files" id="file2" />
</div>
#Html.HiddenFor(model => model.GroupId)
#Html.HiddenFor(model => model.GroupName)
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
}
but the html is being rendered as:
<form action="/Terminals_Policies/Add/1?Length=19" id="form0" method="post">
Anyone know what i have done wrong
Try:
#using (Html.BeginForm("Add", "Terminals_Policies", FormMethod.Post,new{enctype="multipart/form-data"}))
As it should be in the format
Html.BeginForm(action, controller, FormMethod.Post, new { enctype="multipart/form-data"})

Resources