MVC 4 - Validate only one form with multiple partial views - asp.net-mvc-4

I'm working on a MVC 4 exercise project where I've multiple partial views and when I submit on one of this the entire page validates. I want that every button validates only their own forms.
The page looks like this:
This a partial views example:
#model Money.Models.Category
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
#using (Html.BeginForm("Create", "Category", FormMethod.Post, new { id = "createCategoryForm" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Category</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input id="createCategorySubmit" type="submit" value="Create" />
</p>
</fieldset>
}
And this a part of the entire view:
#model Money.Models.Transaction
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Transaction</legend>
<div class="editor-label">
#Html.LabelFor(model => model.CategoryId, "Category")
</div>
<div class="editor-field">
#Html.DropDownList("CategoryId", String.Empty)
#Html.ValidationMessageFor(model => model.CategoryId)
</div>
<div id="createCategory">
#Html.Partial("~/Views/Shared/_CreateCategory.cshtml")
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AccountId, "Accout")
</div>
<div class="editor-field">
#Html.DropDownList("AccountId", String.Empty)
#Html.ValidationMessageFor(model => model.AccountId)
</div>
<div id="createAccount">
#Html.Partial("~/Views/Shared/_CreateAccount.cshtml")
</div>
Have you some idea?
Thank you

You have to parse the new content with the validator:
$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));

Related

Captcha is not loading While adding Screen restriction

I am developing my project in MVC. In registration page i am using captcha control. It is working Fine. But my problem is i am adding screen restriction to some of my pages. While adding screen restriction captcha is not getting loaded.
can anyone please help me?
I have added the screen restriction code below
public class ScreenRestriction : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var routeData = filterContext.HttpContext.Request.RequestContext.RouteData;
string currentAction = routeData.GetRequiredString("action");
string currentController = routeData.GetRequiredString("controller");
string currentArea = routeData.Values["area"] as string;
var request = filterContext.HttpContext.Request;
var response = filterContext.HttpContext.Response;
var session = filterContext.HttpContext.Session;
if ((currentAction != "Login" && currentAction != "Create" && currentAction != "GetUser" && currentAction != "Index" ) == true)
{
if (session["UserID"] == null)
{
if (request.IsAjaxRequest())
{
response.StatusCode = 590;
}
else
{
var url = new UrlHelper(filterContext.HttpContext.Request.RequestContext);
response.Redirect(url.Action("Login", "CU"));
}
filterContext.Result = new EmptyResult();
}
else
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
}
}
}
base.OnActionExecuting(filterContext);
}
Screen restriction in Filters
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new ScreenRestriction());
}
}
I have added the registration page code below
View--
#model SYTMain.Models.tblUser
#using CaptchaMvc.HtmlHelpers
#using CaptchaMvc;
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout_for_registration.cshtml";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>tblUser</legend>
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MiddleName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MiddleName)
#Html.ValidationMessageFor(model => model.MiddleName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EmailID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EmailID)
#Html.ValidationMessageFor(model => model.EmailID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AddressId, "Address1")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.tblAddress.Address1)
#Html.ValidationMessageFor(model => model.tblAddress.Address1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AddressId, "Address2")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.tblAddress.Address2)
#Html.ValidationMessageFor(model => model.tblAddress.Address2)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MobileNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MobileNumber)
#Html.ValidationMessageFor(model => model.MobileNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.WorkNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.WorkNumber)
#Html.ValidationMessageFor(model => model.WorkNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.HomeNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.HomeNumber)
#Html.ValidationMessageFor(model => model.HomeNumber)
</div>
#Html.Captcha(3)
<br />
<p class="Error"> #ViewBag.ErrMessage </p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(tblUser tbluser)
{
string val = System.Configuration.ConfigurationManager.AppSettings["CUTypeId"];
int code = Convert.ToInt32(val);
Session["Emailid"] = tbluser.EmailID.Trim();
if (ModelState.IsValid && this.IsCaptchaValid("Captcha Not Valid") )
{
EmailManager.SendConfirmationEmailName(tbluser.EmailID, tbluser.FirstName);
tbluser.UserTypeId = code;
db.tblUsers.Add(tbluser);
db.SaveChanges();
return RedirectToAction("Login", new { Email = tbluser.EmailID });
}
ViewBag.BusinessCategoryId = new SelectList(db.tblBusinessCategories, "BusinessID", "BusinessName", tbluser.BusinessCategoryId);
ViewBag.UserTypeId = new SelectList(db.tblUserTypes, "UserTypeID", "UserType", tbluser.UserTypeId);
ViewBag.AddressId = new SelectList(db.tblAddresses, "AddressID", "Address1", tbluser.AddressId);
ViewBag.ErrMessage = "Error: Captcha not valid";
return View(tbluser);
}

Getting Parser Error when adding Razor to HTML

I am trying to add razor to my HTML but now I am getting a Parser Error and do not understand why I get this error:
HTML:
#model ServingTeam.DAL.Members
#{
ViewBag.Title = "New Member";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm("AddMember", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { role = "form" }))
{
<div class="row">
<div class="col-md-2">
</div>
<div class="col-sm-6">
<h2>
New Member</h2>
<form class="form-horizontal" role="form" id="memberForm">
<div class="form-group">
<label for="inputName" class="col-sm-2 control-label" />
Name</label>
<div class="col-sm-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", placeholder = "Name", type = "text", required = "required " })
</div>
</div>
<div class="form-group">
<label for="inputName" class="col-sm-2 control-label">
Surname</label>
<div class="col-sm-10">
#Html.TextBoxFor(m => m.Surname, new { #class = "form-control", placeholder = "Surname", type = "text", required = "required " })
</div>
</div>
<div class="form-group">
<label for="inputName" class="col-sm-2 control-label">
Cell</label>
<div class="col-sm-10">
#Html.TextBoxFor(m => m.Cell, new { #class = "form-control", placeholder = "Cell", type = "text" })
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">
Email</label>
<div class="col-sm-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", placeholder = "Enter email address", type = "email", required = "required " })
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-info">
Submit</button>
</div>
</div>
</form>
</div>
<div class="col-md-4">
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script>
$("#memberForm").validate();
</script>
This is the error I get:
Encountered end tag "div" with no matching start tag. Are your start/end tags properly balanced? All works fine when I remove Razor.
Any help please?
I did find one error in your markup, don't know if it has anything to do with your current error though.
<form class="form-horizontal" role="form" id="memberForm">
</form>
the using(Html.BeginForm) will actually create a form for you, now you have a form within the form, which is not wizely
<label for="inputName" class="col-sm-2 control-label" />
Name</label>
There you go. the label gets cancelled out twice.

HttpPost doesn't work into Modal Popup in MVC 4

I have view that has CompanyTable partial view. So this partial view has a CreateBankAccount partial view. Last partial view codes are
#model Invoice.Model.BankAccount
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Launch demo modal
<div id="#Model.TaxID" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
#using (Ajax.BeginForm("CreateModal", "CompanyController", new AjaxOptions { UpdateTargetId = "modal", HttpMethod = "post" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>BankAccount</legend>
#Html.HiddenFor(model => model.ID)
<div class="editor-label">
#Html.LabelFor(model => model.BankName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.BankName)
#Html.ValidationMessageFor(model => model.BankName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CorrespondentAccount)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CorrespondentAccount)
#Html.ValidationMessageFor(model => model.CorrespondentAccount)
</div>
<input type="submit" value="save" />
</fieldset>
}
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<input type="submit" class="btn btn-primary" value=" Save changes" data-dismiss="modal" />
</div>
</div>
so this partial view is modal popup. My problem is that when I want to creat bankAccount my HttpPost method doesn't work, and I return Index action. How I can fix it?

Without editor field item not saving

I am trying to let a user create an object and save it to the database. I have scaffolded it all correctly etc and have modified my control to the following:
Function Create(id As Integer) As ViewResult
ViewBag.id = id
Dim job As Job = New Job
job.CustomerId = id
job.JobAmount = 0
job.JobDate = Date.Now()
job.JobStatus = "Active"
Return View(job)
End Function
This then returns the following view:
#ModelType Laundry.Job
#Code
ViewData("Title") = "Create"
End Code
<h2>Create</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#Using Html.BeginForm()
#Html.ValidationSummary(True)
#<fieldset>
<legend>Job</legend>
<div class="editor-label">
#Html.LabelFor(Function(model) model.JobDate)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.JobDate)
#Html.ValidationMessageFor(Function(model) model.JobDate)
</div>
<div class="editor-label">
#Html.LabelFor(Function(model) model.BillId)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.BillId)
#Html.ValidationMessageFor(Function(model) model.BillId)
</div>
<div class="editor-label">
#Html.LabelFor(Function(model) model.CustomerId)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.CustomerId)
#Html.ValidationMessageFor(Function(model) model.CustomerId)
</div>
<div class="editor-label">
#Html.LabelFor(Function(model) model.JobStatus)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.JobStatus)
#Html.ValidationMessageFor(Function(model) model.JobStatus)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
End Using
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I created a instance of job and passed it through the controller to the view in order to default certain values. Specifically I need to create a job object with the id passed to the controller but I do not want the user to be able to edit this id (they should not see this). I thought that if I simply deleted the following from my view:
<div class="editor-label">
#Html.LabelFor(Function(model) model.CustomerId)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.CustomerId)
#Html.ValidationMessageFor(Function(model) model.CustomerId)
</div>
The object would still save with the customerId I set in my controller however it seems if I delete this code when it saves it saves the customerid as 0 and when its there it works correctly but the user can see and edit it.
Am I doing this correctly?
I do not want the user to be able to edit this id (they should not see this)
Use #Html.HiddenFor(Function(model) model.CustomerId) for this. It will persist the value from view to controller, but not be visible to the user.

Default value on one of the fields in create view

I am trying to set a default value for the scaffold create view that MVC created for me. I have tried creating an instance of the model and passing it to the view but its throwing errors.
Function Create(id As Integer) As ViewResult
Dim job As Job
job.CustomerId = id
Return View(job)
End Function
How would I get my create view to be prepopulated with the id in the parameter using the following view so when a new Job is created it is automatically created with that customer id. My view is below:
#ModelType Laundry.Job
#Code
ViewData("Title") = "Create"
End Code
<h2>Create</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#Using Html.BeginForm()
#Html.ValidationSummary(True)
#<fieldset>
<legend>Job</legend>
<div class="editor-label">
#Html.LabelFor(Function(model) model.JobDate)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.JobDate)
#Html.ValidationMessageFor(Function(model) model.JobDate)
</div>
<div class="editor-label">
#Html.LabelFor(Function(model) model.CustomerId)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.CustomerId)
#Html.ValidationMessageFor(Function(model) model.CustomerId)
</div>
<div class="editor-label">
#Html.LabelFor(Function(model) model.BillId)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.BillId)
#Html.ValidationMessageFor(Function(model) model.BillId)
</div>
<div class="editor-label">
#Html.LabelFor(Function(model) model.JobStatus)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.JobStatus)
#Html.ValidationMessageFor(Function(model) model.JobStatus)
</div>
<div class="editor-label">
#Html.LabelFor(Function(model) model.JobAmount)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.JobAmount)
#Html.ValidationMessageFor(Function(model) model.JobAmount)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
End Using
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I don't necessarily even need to show the customer id on the form but that new object needs to be created with the parameter passed to the controller and the rest of the info the user chooses.
Method 1 : If you want to show the customerId, then you can use the following code...
<div class="editor-label">
#Html.LabelFor(Function(model) model.CustomerId)
</div>
This way, the CustomerId will be displayed, user cannot change it and when postback is done, this value is still present as a part of the model.
Method 2 : If you dont want to display, but still use it for the above purpose, then use the code written below...
<div class="editor-label">
#Html.HiddenFor(Function(model) model.CustomerId)
</div>
Hope this is what you wanted.