I am validating date input server side and adding ModelError if user input is invalid. Following is my code
public ActionResult EditOffer()
{
var offerID = Convert.ToInt64(Request.RequestContext.RouteData.Values["id"]);
using (joyryde_storeEntities context = new joyryde_storeEntities())
{
var objOffer = context.tbl_offer.Where(x => x.LNG_OFFER_ID == offerID).FirstOrDefault();
ViewBag.OfferID = offerID;
ViewBag.Header = "Edit " + objOffer.TXT_OFFER_TITLE;
ViewBag.ActionToPerform = "Edit";
if (System.IO.File.Exists(Server.MapPath(string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], offerID))))
{
objOffer.TXT_OFFER_SMALL_PATH = string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], offerID);
}
return View("AddOffer", objOffer);
}
}
[HttpPost]
public ActionResult EditOffer(tbl_offer modal, string Add, string Edit)
{
if (ModelState.IsValid)
{
using (joyryde_storeEntities context = new joyryde_storeEntities())
{
var offerID = Convert.ToInt64(Request.RequestContext.RouteData.Values["id"]);
if (!isOfferExist(modal.DAT_START_OFFER.Value.Date, modal.DAT_END_OFFER.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(999), Convert.ToInt64(Session["StoreID"]), offerID, Add, Edit, context))
{
// My Code
return RedirectToAction("AllOffers", "Store");
}
else
{
ModelState.AddModelError("DAT_START_OFFER", "Date Not Available"); // Here i am adding Modal Error For Date
if (Edit != null)
{
return RedirectToAction("EditOffer");
}
else
{
return RedirectToAction("AddOffer");
}
}
}
}
else
{
return RedirectToAction("EditOffer");
}
View
<div class="panel-body container-fluid">
#using (Html.BeginForm("EditOffer", "Store", FormMethod.Post, new { #class = "form-horizontal", enctype = "multipart/form-data" , id="offerForm"}))
{
#Html.AntiForgeryToken();
#Html.ValidationSummary(true);
<div class="form-group">
<label class="col-sm-3 control-label">Offer Title</label>
<div class="col-sm-6">
#Html.TextBoxFor(model => model.TXT_OFFER_TITLE, new { #class = "form-control", placeholder = "Offer Title", autocomplete = "off", name = "title" })
#Html.ValidationMessageFor(model => model.TXT_OFFER_TITLE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Offer Banner</label>
<div class="col-sm-9">
<div class="image-container" style=" border: 1px solid #ccc; display: table;position:relative">
<a href="#editimage" data-toggle="modal" class="btn btn-sm btn-icon btn-inverse btn-round btn-image-edit" data-toggle="tooltip" data-original-title="Edit">
<i class="icon wb-pencil" aria-hidden="true"></i>
</a>
<div class="img-preview preview-lg">
<img id="image_upload_preview" src="#Url.Content(string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], ViewBag.OfferID))" style="width:100%" alt="your image" />
</div>
</div>
<div class="input-group-file" style="margin-top:5px">
#Html.TextBoxFor(modal => modal.TXT_OFFER_SMALL_PATH, new { #class = "hide", #readonly = "true", width = "0", id = "filePath" })
#Html.ValidationMessageFor(modal => modal.TXT_OFFER_SMALL_PATH, "", new { #class = "text-danger" })
<span class="">
<span class="btn btn-success btn-small btn-file">
Upload Image <i class="icon wb-upload" aria-hidden="true"></i>
<input type="file" name="files" accept="image/*" multiple="" id="fileupload" onchange="showimagepreview(this)">
</span>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Offer Detail </label>
<div class="col-sm-6">
#Html.TextAreaFor(model => model.TXT_OFFER_TEXT, new { #class = "form-control", placeholder = "Offer Text", autocomplete = "off", name = "text" })
#Html.ValidationMessageFor(model => model.TXT_OFFER_TEXT, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Valid For</label>
<div class="col-sm-4">
<div class="input-daterange" data-plugin="datepicker">
<div class="input-group">
<span class="input-group-addon">
<i class="icon wb-calendar" aria-hidden="true"></i>
</span>
#Html.TextBoxFor(model => model.DAT_START_OFFER, "{0:dd MMMM yyyy}", new { #class = "form-control from_date", placeholder = "Start Date", autocomplete = "off", name = "start" })
#Html.ValidationMessageFor(model => model.DAT_START_OFFER, "", new { #class = "text-danger" })
</div>
<div class="input-group">
<span class="input-group-addon">to</span>
#Html.TextBoxFor(model => model.DAT_END_OFFER, "{0:dd MMMM yyyy}", new { #class = "form-control to_date", placeholder = "End Date", autocomplete = "off", name = "end" })
#Html.ValidationMessageFor(model => model.DAT_END_OFFER, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Is Premium</label>
<div class="col-sm-4">
<div class="radio-custom radio-default radio-inline">
#Html.RadioButtonFor(model => model.INT_IS_PRIME, 1, new { #id = "ispremiumYes", name = "ispremium", #checked = "checked" })
<label for="ispremiumYes">Yes</label>
</div>
<div class="radio-custom radio-default radio-inline">
#Html.RadioButtonFor(model => model.INT_IS_PRIME, 0, new { #id = "ispremiumNo", name = "ispremium", })
<label for="ispremiumNo">No</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-6 col-sm-offset-3">
<button type="submit" name="#ViewBag.ActionToPerform" class="btn btn-primary">Submit </button>
<button type="reset" class="btn btn-default btn-outline">Reset</button>
</div>
</div>
#Html.Hidden("cropWidth", new { id = "cropWidth" })
#Html.Hidden("cropHeight", new { id = "cropHeight" })
#Html.Hidden("cropPointX", new { id = "cropPointX" })
#Html.Hidden("cropPointY", new { id = "cropPointY" })
#Html.Hidden("ImgSrc", new { id = "ImgSrc" })
}
<div class="modal fade" id="editimage" aria-labelledby="modalLabel" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document" style="width:1024px;height:768px">
<div class="modal-content ">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="modalLabel">Crop the image</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-9">
<div class="cropper text-center">
<img id="image" src="#Url.Content(string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], ViewBag.OfferID))" style="max-width:730px;" alt="Picture">
</div>
</div>
<div class="col-sm-3">
<div class="docs-preview clearfix">
<div class="img-preview preview-lg"></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
But Modal Error is not showing on view. What could be the cause ?
When you set your model error then you use RedirectToAction, what mean that you load new page, check in your debug, after that your code go back to GET method and everything is reloaded.
You have to return your View with model.
ModelState.AddModelError("DAT_START_OFFER", "Date Not Available");
if (Edit != null)
{
return View(modal); //if your model is object named modal
}
You didn't see any error because of RedirectToAction. You should use the "View" method. For example you can just write return EditOffer()
If you use return RedirectToAction("EditOffer"); the error will not been show it will be redirect to public ActionResult EditOffer(){} Action method, the [HttpGet] will be shown. To rectify this error, you should use View() method. like return View(); it return the error to the form data posted page.
[HttpPost]
public ActionResult EditOffer(tbl_offer modal, string Add, string Edit)
{
if (ModelState.IsValid)
{
using (joyryde_storeEntities context = new joyryde_storeEntities())
{
var offerID = Convert.ToInt64(Request.RequestContext.RouteData.Values["id"]);
if (!isOfferExist(modal.DAT_START_OFFER.Value.Date, modal.DAT_END_OFFER.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(999), Convert.ToInt64(Session["StoreID"]), offerID, Add, Edit, context))
{
// My Code
return RedirectToAction("AllOffers", "Store");
}
else
{
ModelState.AddModelError("DAT_START_OFFER", "Date Not Available"); // Here i am adding Modal Error For Date
if (Edit != null)
{
return View(modal);
}
else
{
return RedirectToAction("AddOffer");
}
}
}
}
else
{
ViewBag.OfferID = Here give the office id;
ViewBag.Header = "Edit " + objOffer.TXT_OFFER_TITLE;
ViewBag.ActionToPerform = "Edit";
ModelState.AddModelError("","Your Error Message"); // Here i am adding Modal Error For Date
return View(modal);
}
}
Related
I'm trying to submit my form using Ajax.beginform. I tried everything but i am getting this resource cannot found error.
I have two models - PatientEligibility and PatientDetails. Both contains 10-12 properties respectively.
I have created on viewmodel using those two models and I am trying to use some of the properties in one partial view and submitting that data button click
my view -
#model Portal.Models.EligibilityViewModel
<script type="text/javascript">
$(document).ready(function () {
$('input[type="checkbox"]').on('change', function () {
$('input[name="' + this.name + '"]').not(this).prop('checked', false);
});
});
</script>
<div class="row margin-top-0">
<div class="col-xs-12 col-sm-12">
<h4><b>Patient Eligibility</b></h4>
</div>
</div>
#using (Ajax.BeginForm("SubmitPatientEligibility", "Ophthalmic", new AjaxOptions { OnSuccess = "OnSuccess", OnFailure = "OnFailure" }))
{
<div class="row margin-top-10">
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<div class="checkbox">
<label>
#Html.CheckBoxFor(model => model.PatientEligibility.IsAboveSixty, new { #Name = "cbAgeEligibility", htmlAttributes = new { id = "cbAbvSixty", #class = "form-control", Name = "group1[]" } })
The patient is 60 or over
</label>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<div class="checkbox">
<label>
#Html.CheckBoxFor(model => model.PatientEligibility.IsBelowSixteen, new { #Name = "cbAgeEligibility", htmlAttributes = new { id = "cbUnderSixteen", #class = "form-control", Name = "group1[]" } })
The patient is under 16
</label>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<div class="checkbox">
<label>
#Html.CheckBoxFor(model => model.PatientEligibility.IsBetweenForty, new { #Name = "cbAgeEligibility", htmlAttributes = new { id = "cbAbovenForty", #class = "form-control", Name = "group1[]" } })
The patient is 40 or over and is the parent/brother/sister/child of a person who has or has had gloucoma
</label>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<div class="checkbox">
<label>
#Html.CheckBoxFor(model => model.PatientEligibility.IsStudent, new { #Name = "cbAgeEligibility", htmlAttributes = new { id = "cbStudent", #class = "form-control", Name = "group1[]" } })
The patient is full time student aged 16, 17 or 18 at the establishment below.
</label>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<div class="checkbox">
<label>
#Html.CheckBoxFor(model => model.PatientEligibility.IsPrisoner, new { data_toggle = "collapse", data_target = "#dvseenNotseen", htmlAttributes = new { id = "cbPrisoner", #class = "form-control" } })
The patient is prisoner on leave from the prison detailed below
</label>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
#Html.LabelFor(p => p.PatientBenefit.NINNumber)
#Html.EditorFor(model => model.PatientBenefit.NINNumber, new { htmlAttributes = new { #class = "form-control", autocomplete = "off" } })
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<label>DATE OF BIRTH</label>
#Html.TextBoxFor(model => model.PatientBenefit.DOB, new { #class = "form-control", autocomplete = "off", #id = "datetimepicker1" })
</div>
</div>
<div class="row margin-top-10">
<div class="col-xs-12 col-sm-3">
<button class="btn btn-default" name="btnBack">Previous</button>
</div>
<div class="col-xs-12 col-sm-9 text-right">
<button class="btn btn-default" name="btnBack">Save Draft</button>
<button class="btn btn-success fa fa-chevron-right icon-right" name="btnNext" type="submit">Next</button>
</div>
</div>
}
and my model is like this -
public class EligibilityViewModel
{
public PatientEligibility PatientEligibility { get; set; }
public PatientBenefit PatientBenefit { get; set; }
}
I am trying to call this method on submit of Next button -
public class OphthalmicController : Controller
{
[HttpPost]
public ActionResult SubmitPatientEligibility(EligibilityViewModel model)
{
return null;
}
}
i dont know why but i am getting this 500 error resource cannot found for this method.
What am I missing here?
I have project in which there is a form to edit user details. Initially it is disabled but when user search particular user and click edit button everything is enabled. I capture all changed data except dropdown list newly selected value. when user changed data and submit form. on the server end model property for dropdownlist contains old value in place new changed value.
Please help me
<script>
function Validate(strDecision) {
//alert("Validate");
debugger;
if (strDecision == "EDIT") {
if ($("#MerchDispName").val() == "" || $("#MerchDispName").val() == null) {
$("#DivInfoNErrorMsg").addClass("alert-danger");
$("#DivInfoNErrorMsg").html("<span>There is no data for editing.</span>");
$("#DivInfoNErrorMsg").show();
return false;
}
else {
debugger;
$(".ReadOnly").removeAttr("readOnly", "readOnly");
$(".Disabled").removeAttr("disabled", "disabled");
$("#Update").show();
$("#Edit").hide();
GetDetails();
}
}
else
{
var bFlag = false;
var iLengthPaymentMode = '#Model.dicPaymentModeVal.Count';
var iLengthProgramType = '#Model.dicProgramTypeVal.Count';
var i = 1;
for (; i <= iLengthPaymentMode; ) {
if ($("#PaymentCB" + i).is(":checked")) {
$("#PaymentCB" + i + "hid").val($("#PaymentCB" + i).val());
bFlag = true;
}
i++;
}
if (bFlag == false) {
$("#PaymentCBmsg").html("<span style='color:Red'>*Please select at least one payment option.</span>");
ShowErrorMsg("Please select at least one payment option.");
$("#PaymentCBmsg").show();
return false;
}
for (; i <= iLengthProgramType; ) {
if ($("#ProgramCB" + i).is(":checked")) {
$("#ProgramCB" + i + "hid").val($("#ProgramCB" + i).val());
bFlag = true;
}
i++;
}
if (bFlag == false) {
$("#ProgramCBmsg").html("<span style='color:Red'>*Please select at least one program type.</span>");
ShowErrorMsg("Please select at least one program type.");
$("#ProgramCBmsg").show();
return false;
}
else {
$(".Disabled").attr("disabled", "disabled");
$(".ReadOnly").attr("readOnly", "readOnly");
$("#Edit").show();
$("#Update").hide();
$("#frmMerchantEDIT").submit();
}
}
}
$(document).ready(function () {
//debugger;
var bFlagErrorMessage = '#Model.FlagErrorMessage';
var bFlagInfoMessage = '#Model.FlagInfoMessage';
$('#CountryList').on('change', function () {
debugger;
var id = this.value;
//$("#CountryID").val('0');
$("#CountryID").val(id); // or $(this).val()
});
$('#StateList').on('change', function () {
debugger;
var id = this.value;
//$("#StatesID").val('0');
$("#StatesID").val(id);
alert(id); // or $(this).val()
});
$('#CityList').on('change', function () {
debugger;
var id = this.value;
//$("#CityID").val('0');
$("#CityID").val(id);
//alert(this.value); // or $(this).val()
});
if (bFlagErrorMessage == 'True') {
debugger;
var sErrorMsg = '#Model.ErrorMessage';
$("#DivInfoNErrorMsg").addClass("alert-danger");
$("#DivInfoNErrorMsg").html("<span>" + sErrorMsg + "</span>");
$("#DivInfoNErrorMsg").show();
$(".ReadOnly").removeAttr("readOnly", "readOnly");
$(".Disabled").removeAttr("disabled", "disabled");
$("#Update").show();
$("#Edit").hide();
}
if (bFlagInfoMessage == 'True') {
debugger;
var sErrorMsg = '#Model.InfoMessage';
$("#DivInfoNErrorMsg").addClass("alert-success");
$("#DivInfoNErrorMsg").html("<span>" + sErrorMsg + "</span>");
$("#DivInfoNErrorMsg").show();
}
});
</script>
#using (Html.BeginForm("EDIT_MERCHANT", "MERCHANT_Permission", FormMethod.Post, new { #id = "frmMerchantEDIT", #class = "form-horizontal", #Role = "form" }))
{
#Html.AntiForgeryToken()
//#Html.ValidationSummary()
<div class="logmain_mechant">
<fieldset>
<legend class="panel-heading panel-primary" style="font-size:140%">Edit Merchant</legend>
<div id="DivInfoNErrorMsg" class="alert" hidden="hidden"></div>
<div class="wrapper">
<div class="panel-group" id="accordion">
<div class="panel panel-primary">
<div class="panel-heading">
<a class="accordion-toggle" style="text-decoration:none" data-toggle="collapse"
data-parent="#accordion" href="#collapseOne">
<h2 class="panel-title" style="color:White;font-size:135%">
Personal
<span class="indicator glyphicon glyphicon-chevron-down pull-right"></span>
</h2>
</a>
</div>
<div id="collapseOne" class="panel-collapse collapse in">
<div class="panel-body">
<div class="form-group">
<label for="MerchantName" class="control-label col-xs-8 col-sm-6 col-md-4">Merchant Name<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.MerchantName, new { #id = "MerchantName", #class = "form-control ReadOnly",#onclick= "ErrorDivHide()" })
#Html.ValidationMessageFor(m => m.MerchantName)
</div>
</div>
<div class="form-group">
<label for="MerchDispName" class="control-label col-xs-8 col-sm-6 col-md-4">Merchant Display Name<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.MerchantDisplayName, new { #id = "MerchDispName", #class = "form-control", #onclick="hideme()",#placeholder="Merchant Display Name" })
#Html.ValidationMessageFor(m => m.MerchantDisplayName)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">Address1<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.Address1, new { #id = "Address1", #class = "form-control ReadOnly", #onclick = "ErrorDivHide()" })
#Html.ValidationMessageFor(m => m.Address1)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col- md-4">Address2:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.Address2, new { #id = "Address2", #class = "form-control ReadOnly", #onclick = "ErrorDivHide()" })
#Html.ValidationMessageFor(m => m.Address2)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">Address3:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.Address3, new { #id = "Address3", #class = "form-control ReadOnly", #onclick = "ErrorDivHide()" })
#Html.ValidationMessageFor(m => m.Address3)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">Country<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.DropDownListFor(m => m.CountryID, Model.liCountry, new { #id = "CountryList", #class = "form-control Disabled", #onchange = "GetStates()", #onclick = "ErrorDivHide()" })
#Html.HiddenFor(m => m.CountryID, new { #id="CountryId" })
#*#Html.TextBoxFor(m => m.CountryName, new { #id = "CountryName", #calss = "form-control" })*#
#Html.ValidationMessageFor(m => m.CountryID)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">State<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.DropDownListFor(m => m.StateID, Model.liState, new { #id = "StateList", #class = "form-control Disabled", #onchange = "GetCitis()", #onclick = "ErrorDivHide()" })
#Html.HiddenFor(m => m.StateID, new { #id = "StateIds" })
#*#Html.TextBoxFor(m => m.CountryName, new { #id = "CountryName", #calss = "form-control" })*#
#Html.ValidationMessageFor(m => m.StateName)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">City<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.DropDownListFor(m => m.CityID, Model.liCity, new { #id = "CityList", #class = "form-control Disabled", #onclick = "ErrorDivHide()" })
#Html.HiddenFor(m => m.CityID, new { #id = "CityIds" })
#*#Html.TextBoxFor(m => m.CountryName, new { #id = "CountryName", #calss = "form-control" })*#
#Html.ValidationMessageFor(m => m.CityName)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">ZipCode<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.ZipCode, new { #id = "ZipCode", #class = "form-control ReadOnly", #onclick = "ErrorDivHide()", #onkeypress = "return validateZipCode(event);" })
#Html.ValidationMessageFor(m => m.ZipCode)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-10 col-sm-6 col-md-4">PG Merchant Name</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#*type="text" name="PayControllerMerName" id="PayControllerMerName" class="form-control" />*#
#Html.TextBoxFor(m => m.sPGMerchantName, new { #id = "PayControllerMerName", #class = "form-control ReadOnly", #onclick = "ErrorDivHide()" })
#Html.ValidationMessageFor(m => m.sPGMerchantName)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">PG Merchant ID<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.PayControllerMerID, new { #name = "PayControllerMerID", #id = "PayControllerMerID", #class = "form-control disabled" })
#Html.ValidationMessageFor(m => m.PayControllerMerID)
</div>
</div>
#*<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>*#
</div>
</div>
</div>
<div class="panel panel-primary">
<div class="panel-heading">
<a class="accordion-toggle" data-toggle="collapse" style="text-decoration:none" data-parent="#accordion" href="#collapseTwo">
<h2 class="panel-title" style="color:White;font-size:135%">
Configuration
<span class="indicator glyphicon glyphicon-chevron-down pull-right"></span>
</h2>
</a>
</div>
<div id="collapseTwo" class="panel-collapse collapse">
<div class="panel-body">
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">Merchant Website<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.ReturnURL, new { #id = "ReturnURL", #class = "form-control ReadOnly", #onclick = "ErrorDivHide()" })
#Html.ValidationMessageFor(m => m.ReturnURL)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">Merchant EmailID<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#Html.TextBoxFor(m => m.EmailID, new { #id = "EmailID", #class = "form-control ReadOnly", #onclick = "ErrorDivHide()" })
#Html.ValidationMessageFor(m => m.EmailID)
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">Program Type<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#{
var i = 1;
foreach (KeyValuePair<int, string> k in Model.dicProductType)
{
var ProductName = "ProgramCB" + i;
<span class="col-sm-offset-1 pull-left">
<input type="checkbox" name="ProgramCB" value="#k.Key"
checked="#Model.dicProgramTypeVal[k.Key]" id="#ProductName" class="Disabled"
onclick="ProgramClick(#ProductName)" /><label for="#ProductName" style="font-weight:normal;">#k.Value</label> </span>
i = i + 1;
ProductName = ProductName + "hid";
<input type="hidden" id="#ProductName" name="ProgramCB" />
}
}
</div>
<div hidden="hidden" id="ProgramCBmsg"></div>
</div>
<div class="form-group">
<label class="control-label col-xs-8 col-sm-6 col-md-4">Payment Mode<span style="color:Red">*</span>:</label>
<div class="col-xs-12 col-sm-10 col-md-8">
#{
i = 1;
foreach (KeyValuePair<int, string> k in Model.dicPaymentMode)
{
var elementName = "PaymentCB" + i;
<input type="checkbox" name="PaymentCB"
value="#k.Key" class="Disabled"
checked="#Model.dicPaymentModeVal[k.Key]"
id="#elementName" onclick="PaymentClick(#elementName)" />
<label for="#elementName"
style="font-weight:lighter;font-size:normal">#k.Value</label>
i = i + 1;
elementName = elementName + "hid";
<input type="hidden" id="#elementName" name="PaymentCB" />
}
}
</div>
#Html.HiddenFor(m => m.CurrentStateID, new { #id="StatesID"})
#Html.HiddenFor(m => m.CurrentCountryID, new { #id = "CountryID" })
#Html.HiddenFor(m => m.CurrentCityID, new { #id = "CityID" })
<div hidden="hidden" id="PaymentCBmsg"></div>
</div>
</div>
</div>
</div>
<div class="panel panel-default" id="Button">
<span style="color:Red">* Required Fields</span>
<div class="col-xs-12 col-sm-10 col-md-8 pull-right">
<button type="button" class="btn btn-default pull-right"
onclick="Validate('UPDATE')" id="Update">Update</button>
<button type="button" class="btn btn-default pull-right"
onclick="Validate('EDIT')" id="Edit">Edit</button>
</div>
</div>
<div hidden="hidden">
<button type="button" class="btn btn-default" id="btnClear" onclick="Clear();" style="display: none;">Clear</button>
</div>
</div>
</div>
</fieldset>
</div>
}
Server side code
if (objMerchant.CurrentCityID != 0 && objMerchant.CurrentCityID != objMerchant.CityID)
objMerchant.CityID = objMerchant.CurrentCityID;
if (objMerchant.CurrentStateID != 0 && objMerchant.CurrentStateID != objMerchant.StateID)
objMerchant.StateID = objMerchant.CurrentStateID;
if (objMerchant.CurrentCountryID != 0 && objMerchant.CurrentCountryID != objMerchant.CountryID)
objMerchant.CountryID = objMerchant.CurrentCountryID;
What i think going wrong is the Hidden control. Your code with dropdownlist contains
#DropDownListFor and #HiddenFor due to which there will be two input with same name and id, and when you are submitting your form. It is taking from the hidden input.
Try to remove the hidden control, because it is not correct to have same id for more than one element in html
I hope this will solve your porblem.
I have a label and a checkbox in my view that I would like next to each other. However, as you can see in this picture I cannot get them any closer.
Here is my view code:
#using (Html.BeginForm("AddTechNote", "Ticket", FormMethod.Post)) { #Html.AntiForgeryToken()
<div class="form-group">
#Html.HiddenFor(model => model.TicketId)
<div class="col-md-12 col-xs-12">
<div class="col-md-3">
#Html.Label("New Note", new { #class = "control-label" })
</div>
<div class="col-md-1" style="text-align: right">
#Html.Label("Public", new { #class = "control-label" })
</div>
<div class="col-md-1">
#Html.CheckBox("PublicNote", new { #class = "chk=style", #checked = "checked" })
</div>
</div>
<div class="col-md-12 col-xs-12">
#Html.TextArea("Note", new { cols = 600, #rows = 5 })
</div>
<div class="form-group">
<div class="col-md-2">
<input type="submit" value="Add" class="btn btn-default" />
</div>
#*<div class="col-md-1 col-lg-offset-1">
</div>
*#
</div>
</div>
}
Jesus,
This is what I get with the code you provided. Thank you for your help so far.
You can do following:
Use only one div for both label and checkbox like:
<div class="col-md-1" style="text-align: right">
#Html.Label("Public", new { #class = "control-label" })
#Html.CheckBox("PublicNote", new { #class = "chk=style", #checked = "checked" })
</div>
The label need to wrap the input.
You need to change your Razor view, something like this:
<div class="#Model.ControlDimension">
<div class="checkbox #Model.CheckBoxDivClasses">
<label for="#Model.ControlName">#Html.Raw(Model.Label)#Model.ControlFor</label>
#Model.ValidationMessageFor
</div>
</div>
The control needs to be inside the label element.
In your case, I think ...:
<div class="col-md-2">
<div class="checkbox">
<label for="PublicNote">
Public
#Html.CheckBox("PublicNote", new { #class = "chk=style", #checked = "checked" })
</label>
</div>
</div>
I have the following view:
#model GRCWebApp.ViewModels.NewClubInterestsViewModel
#{
ViewBag.Title = "Add Club Interests";
}
<div class="col-md-10 col-offset-md-1">
<h2 class ="text-success">Add Club Interests for #Html.DisplayFor(model => model.Name)</h2>
</div>
#using (Html.BeginForm("NewInterests", "Club", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="row">
<div class="col-md-8">
<div class="well bs-component">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(x => Model.ClubId)
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<h3>Tick the areas your club is interested/runs events in</h3>
</div>
</div>
<div class="col-md-offset-1">
#for (int i = 0; i < Model.ClubTypeInterests.Count(); i++)
{
<div>
#Html.HiddenFor(x => Model.ClubTypeInterests[i].InterestId)
#Html.CheckBoxFor(x => Model.ClubTypeInterests[i].selected)
#Html.LabelFor(x => Model.ClubTypeInterests[i].InterestName, Model.ClubTypeInterests[i].InterestName)
</div>
}
</div>
<div class="form-group">
<div class="row">
<div class="col-md-offset-1 col-md-12">
<input type="submit" name="Submit" value="Next" class="btn btn-success btn-lg" /> to setup Online membership
<input type="submit" name="Submit" value="Complete" class="btn btn-warning btn-sm" /> to just provide online event entries
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
#using (Html.BeginForm("AddInterest", "Club"))
{
#Html.AntiForgeryToken()
<hr />
<div class="row">
<div class="col-md-8">
<div class="well bs-component">
<div class="form-group">
<div class="col-md-12 col-md-offset-1">
<h3>Not listed? - Add extras here</h3>
</div>
</div>
#Html.HiddenFor(model => model.ClubTypeId)
#Html.HiddenFor(model => model.ClubId)
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-inline">
<div class="form-group">
<div class="row col-md-offset-1 col-md-11">
<div class="col-md-4">
#Html.LabelFor(model => model.InterestName, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.InterestName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.InterestName, "", new { #class = "text-danger" })
</div>
<div class="col-md-5">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
<input type="submit" value="Add" class="btn btn-info" style="margin-top: 22px" />
</div>
</div>
</div>
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Overtime the page loads the Validation message shows for InterestName in the second form AddInterest.
The Get method for the whole form is:
[HttpGet]
public ActionResult NewInterests(NewClubInterestsViewModel model, int id)
{
//Find the Club and then pass its id to the ViewModel
var club = db.Clubs.Find(id);
//model.ClubId = club.ClubId ;
//Interests List
IEnumerable<Interest> allExistingInterests;
//Generate a list of the interests that apply to that type of club
using (ApplicationDbContext context = new ApplicationDbContext())
{
allExistingInterests = context.Interests
.Where(s => s.ClubTypeId == club.ClubTypeId)
.OrderBy(s => s.InterestName)
.ToList();
}
IEnumerable<int> clubInterestIds = club.ClubInterests.Select(x => x.InterestId).ToList();
//Generate the ViewModel with the appropriate Interests
var viewModel = new NewClubInterestsViewModel
{
ClubId = club.ClubId,
Name = club.Name,
ClubTypeId = club.ClubTypeId,
ClubTypeInterests =
allExistingInterests.Select(
x => new ClubInterestsViewModel { InterestId = x.InterestId, InterestName = x.InterestName, selected = clubInterestIds.Contains(x.InterestId) }).ToArray()
};
return View(viewModel);
}
What do I need to do to stop the validation message showing on load?
Remove the NewClubInterestsViewModel model parameter from your GET method. It should be just
public ActionResult NewInterests(int id)
The first step in the model binding process is that instances of your parameters are initialized and then its properties are set based on form values, route values, query string values etc. In your case there are no values to set, so the properties of your model are their defaults, but because you have validation attributes on your properties, validation fails and errors are added to ModelState which are then displayed in the view.
I want to submit a single text field in a form. I have this view:
#model SenecaFormsServer.Areas.Dashboard.Models.EditProductModel
#using SenecaFormsServer.Areas.Dashboard.Models
#using Seneca.SfsLib.Connectors
<div id="ConnectorSettings-MAIL_PRODUCT_HANDLERS">
<h4>#Resources.Entity.Product.SettingsForConnector: Mail product handlers</h4>
#{
MailProductHandlersModel mailModel = Model.ConnectorModels["MAIL_PRODUCT_HANDLERS"] as MailProductHandlersModel;
}
<div class="form-group">
#Html.Label(Resources.Entity.Product.Sender, new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.Editor("MailProductHandlers_sender", new { htmlAttributes = new { #class = "form-control", #Value = mailModel.Sender, #placeholder = Model.CustomerConfig.DefaultSenderAddress } })
</div>
</div>
<div class="form-group">
#Html.Label(Resources.Entity.Product.MailSubject, new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.Editor("MailProductHandlers_subject", new { htmlAttributes = new { #class = "form-control", #Value = mailModel.Subject } })
</div>
</div>
<!--
<div class="form-group">
#Html.Label("Reply to form submitter", new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.CheckBox("MailProductHandlers_replytoFormSubmitter", new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
-->
<div class="form-group">
#Html.Label(Resources.Entity.Product.MailMessage, new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.EditorFor(model => mailModel.Message, new { htmlAttributes = new { #class = "form-control tiny-mce", data_lang = System.Globalization.CultureInfo.CurrentUICulture.Name } })
#Html.ValidationMessageFor(model => mailModel.Message)
#*#Html.TextArea("MailProductHandlers_message", mailModel.Message, new { #class = "form-control", #rows = 15 })*#
</div>
</div>
<div class="form-group">
#Html.Label(Resources.Entity.Product.GeneratePDF, new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.Label(Resources.Entity.Product.GeneratePDFYes) #Html.RadioButtonFor(model => model.IsChecked, true, new { #checked = "checked", #class = "pdfchecker" })
#Html.Label(Resources.Entity.Product.GeneratePDFNo) #Html.RadioButtonFor(model => model.IsChecked, false, new { #class = "pdfchecker" })
</div>
</div>
<div class="form-group">
<div id="hideLable">
#Html.Label(Resources.Entity.Product.PdfMessage, new { #class = "text-bold control-label col-md-2" })
</div>
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.EditorFor(model => mailModel.PdfMessage, new { htmlAttributes = new { #class = "form-control tiny-mce", #id = "mceu_61", data_lang = System.Globalization.CultureInfo.CurrentUICulture.Name } })
#Html.ValidationMessageFor(model => mailModel.PdfMessage)
</div>
</div>
#using (Html.BeginForm("GeneratePDFFromHtml", "Product", FormMethod.Post)) {
#Html.AntiForgeryToken()
<div class="col-xs-12 padding-bottom-10">
#*<i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF *#
<button type="submit" value="Save" class="btn btn-success"><i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF</button>
</div>
}
And I want to submit this part:
#using (Html.BeginForm("GeneratePDFFromHtml", "Product", FormMethod.Post)) {
#Html.AntiForgeryToken()
<div class="col-xs-12 padding-bottom-10">
#*<i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF *#
<button type="submit" value="Save" class="btn btn-success"><i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF</button>
</div>
}
and this is the action method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult GeneratePDFFromHtml(EditProductModel model, string data, string designId)
{
string customerSchema = SfsHelpers.StateHelper.GetSchema();
//TemplateLibraryEntry entry = GetTemplateLibraryEntry(designId, customerSchema);
SubmittedForm sf = new SubmittedForm();
string schema = requestSchema;
customer_DbConnection db = new customer_DbConnection();
RenderFormController renderController = new RenderFormController();
renderController.GeneratePdf(data, db,sf);
//return RedirectToAction(model.DesignId, "Prdocut/Edit");
return Content("It works");
}
</div>
but the action method is not been triggered.
How to trigger the action method?
There has be created a PDF file from this textfield:
#using (Html.BeginForm("GeneratePDFFromHtml", "Product", null, FormMethod.Post, new { enctype = "multipart/form-data" })) {
#Html.AntiForgeryToken()
<div class="form-group">
<div id="hideLable">
#Html.Label(Resources.Entity.Product.PdfMessage, new { #class = "text-bold control-label col-md-2" })
</div>
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.EditorFor(model => mailModel.PdfMessage, new { htmlAttributes = new { #class = "form-control tiny-mce", #id = "mceu_61", data_lang = System.Globalization.CultureInfo.CurrentUICulture.Name } })
#Html.ValidationMessageFor(model => mailModel.PdfMessage)
</div>
</div>
<div class="col-xs-12 padding-bottom-10">
<i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF
#*<button type="submit" value="Save" class="btn btn-success"><i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF</button>*#
</div>
}
and this is also the action method that has to been triggered and create the PDF file. But the method is not been triggered in the controller
The problem is that it is a partial view. So I solved like this:
Jquery:
$(document).ready(function () {
$('#btnGeneratePDF').click(function () {
var form = document.createElement("form");
form.setAttribute("GeneratePDFFromHtml", "post");
form.setAttribute("action", "GeneratePDFFromHtml");
form.setAttribute("target", "_blank");
var hiddenField = document.createElement("btnGeneratePDF");
//hiddenField.setAttribute("name", "search");
//hiddenField.setAttribute("value", "product1,product2");
hiddenField.setAttribute("type", "hidden");
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();
});
});
and the view looks like now this:
<form method="post" id="form" name="form" action="#Url.Action("GeneratePDFFromHtml", "Product")" enctype="multipart/form-data">
<fieldset>
<div class="form-group">
<div id="hideLable">
#Html.Label(Resources.Entity.Product.PdfMessage, new { #class = "text-bold control-label col-md-2" })
</div>
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.EditorFor(model => mailModel.PdfMessage, new { htmlAttributes = new { #class = "form-control tiny-mce", #id = "mceu_61", data_lang = System.Globalization.CultureInfo.CurrentUICulture.Name } })
#Html.ValidationMessageFor(model => mailModel.PdfMessage)
</div>
</div>
<div class="col-xs-12 padding-bottom-10">
#*<i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF *#
<button type="submit" value="Create" class="btn btn-success" id="btnGeneratePDF" name="btnGeneratePDF" formtarget="_blank" onclick="GeneratePDFFromHtml()"><i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF</button>
</div>
</fieldset>
</form>
but the url is now like this, after I press on the button:
http://localhost:51098/Dashboard/Product/Edit/GeneratePDFFromHtml?
what is ofcourse not correct. so how to trigger the method in the controller?
I get also this warning: Uncaught ReferenceError: GeneratePDFFromHtml is not defined