I have two validations in my action like so:
if (viewModel.IssuePDFFile == null || viewModel.IssuePDFFile.ContentLength == 0)
{
ModelState.AddModelError("", "Please select a file to upload.");
if (selectedJournalId > 0)
{
return RedirectToAction("CreateNewIssue", new { journalId = selectedJournalId });
}
else
{
return RedirectToAction("CreateNewIssue",
new { journalId = selectedJournalId, journalName = viewModel.JournalName });
}
}
var fileInfo = new FileInfo(viewModel.IssuePDFFile.FileName);
if (!StaticData.AcceptedContentTypes.Contains(viewModel.IssuePDFFile.ContentType,
StringComparer.InvariantCultureIgnoreCase) ||
!fileInfo.Extension.Equals(".pdf", StringComparison.InvariantCultureIgnoreCase))
{
ModelState.AddModelError("IssuePDFFile", "You can only select a PDF file.");
if (selectedJournalId > 0)
{
return RedirectToAction("CreateNewIssue", new { journalId = selectedJournalId });
}
else
{
return RedirectToAction("CreateNewIssue", new { journalId = selectedJournalId,
journalName = viewModel.JournalName });
}
}
And in my view, I have this:
#using (Html.BeginForm(...)
{
#Html.ValidationSummary(false, "", new { #class = "text-danger" })
#*File*#
<div class="form-group">
#Html.LabelFor(model => model.IssuePDFFile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-12">
<input type="file" id="File" name="issuePDFFile" placeholder="Select a file to upload" />
#Html.ValidationMessageFor(model => model.IssuePDFFile, "", new { #class = "text-danger" })
</div>
</div>
...
}
Please note that the excludePropertyErrors argument in the call to the #Html.ValidationSummary extension is set to false in the hope that errors that I myself add to the model state errors collection using keys other than my property names will also show up in the summary.
However, the two error messages shown in the code snippet above do not show up anywhere, neither in the validation summary, nor in the ValidationFor place where I think at least one of them, the one I have added a key for, should show up?
It looks like you are performing a redirect after writing errors to your modelstate. Redirecting will loose the modelstate, as it is only valid for the lifetime of the request, which ends when you redirect.
The solution is to
return View(Model) //customise as necessary
rather than your current
return RedirectToAction()
Writing the response back to the client within the same reuqest will mean the Modelstate is available to use, and display the errors.
Related
Below View Code. when i click on Create button without Selecting Activity. it is not showing validation message. i am using Required attribute in Model Class
<div class="form-group">
#Html.LabelFor(model => model.TransactionTypeID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TransactionTypeID, new SelectList(ViewBag.GetT, "TransactionTypeID", "TransactionType"), "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TransactionTypeID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ActivityID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ActivityID, new SelectList(ViewBag.GetA, "ActivityID", "ActivityName"), "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActivityID, "", new { #class = "text-danger" })
</div>
</div>
//Controller code
public ActionResult Create()
{
List<TransactionTypeMaster> T = new DATransactionTypeMaster().GetListAll();
ViewBag.GetT = T;
List<ActivityMaster> A = new DAActivityMaster().GetListAll();
ViewBag.GetA = A;
return View();
}
Can Any One Help on this. Need To Know Where i m going Wrong
when i click on Create button without Selecting Activity. it is not showing validation message. i am using Required attribute in Model Class
try giving the default '--Select--' options in your drop downs a value of 0.
In your model, make sure your drop down value is set to '[Required]' and also give it the attribute:
[Range(1, Int32.MaxValue, ErrorMessage = "Must Select A Value")]
basically letting it only accept values > 0
I think you TransactionTypeID is int, make that Nullable that would fix this issue. Currently it doesn't work because by default it might be sending zero as a value by using null, it would send null when user doesn't touch this field.
I added the Bootstrap dual listbox plugin on my project and it's working fine, but how can I pass the contents of the selected listbox to my controller? It's already inside a form but if I try to get it through FormCollection it returns as null.
View:
<div class="form-group col-md-7" style="margin-left: -15px;">
<select style="display: none;" multiple="multiple" size="10" name="dualListbox" id="dualListbox" class="demo2">
#if (ViewData["Customers"] != null)
{
foreach (var item in ViewData["Customers"] as List<Testbox.Models.Customer>)
{
<option value="customer">#item.NAME #item.LName - #item.PHONE11</option>
}
}
</select>
</div>
Well you can do it as below:
I'll assume that your form id is demoform and below is how the post action method will look like:
[HttpPost]
public ActionResult GetForm()
{
string values = Request.Form["dualListbox"];
//Form[key] will be 'name' property of your select box
//You will get values as comma ',' separated values like option 1,
//option 2, option 4 etc., and I hope you know how you can get each
//options by splitting the comma separated values.
......
......
}
Here is an example to your question. Maybe this will help people in the future.
The trick is in the JS.
Let's say you want to use Bootstrap Dual Listbox in conjuction with ASP.NET MVC 4 and Kendo framework.
We will use the Razor syntax and C#.
First, we write in the view the placeholder for the code. We will be linking a kendo control and the Bootstrap Dual Listbox
<script>
var urlGetCascadeMultiSelectBrandTypeByBrand = "#(Url.Action("GetCascadeMultiSelectBrandTypeByBrand", "DropDownList"))";
</script>
<div class="col-md-12 col-sm-12 col-xs-12 padding-0 ">
<div class="col-md-6 col-sm-6 col-xs-12">
#Html.LabelFor(m => m.BrandId)<br />
#(Html.Kendo().DropDownListFor(m => m.BrandId)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCascadeDdlBrandBySegment", "DropDownList")
.Data("filterSegments");
})
.ServerFiltering(true);
})
.DataTextField("BrandName")
.DataValueField("BrandId")
.Filter(FilterType.Contains)
.CascadeFrom("SegmentId")
.OptionLabel("Select brand")
.Events(evt => evt.Change("onBrandIdDdlChange"))
.HtmlAttributes(new { #style = "width: 100%;" }))
#Html.ValidationMessageFor(m => m.BrandId)
</div>
<div class="col-md-6 col-sm-6 col-xs-12">
</div>
</div>
<div class="clear height10"></div>
<div class="col-md-12 col-sm-12 col-xs-12 padding-0 ">
<div class="col-md-12 col-sm-12 col-xs-12">
#Html.LabelFor(m => m.BrandTypeIdList)<br />
#if (Model.IsEdit)
{
#Html.ListBoxFor(m => m.BrandTypeIdList, Html.GetBrandTypeByBrandIdSelectListItemsList(Model.BrandId))
}
else
{
#Html.ListBoxFor(m => m.BrandTypeIdList, new List<SelectListItem>())
}
#Html.ValidationMessageFor(m => m.BrandTypeIdList)
</div>
</div>
Then, we create the C# helper code to go with it.
public static IEnumerable<SelectListItem> GetBrandTypeByBrandIdSelectListItemsList(this HtmlHelper htmlHelper, int brandId)
{
using (var dbContext = new Entities())
{
return dbContext.BrandType.Where(x => x.Active == true && x.BrandId == brandId).Select(BrandTypeToDdlSelector).ToList();
}
}
public static Func<BrandType, SelectListItem> BrandTypeToDdlSelector
{
get
{
return (x => new SelectListItem()
{
Value = x.BrandTypeId.ToString(),
Text = x.Name
});
}
}
public JsonResult GetCascadeMultiSelectBrandTypeByBrand(int? brandId)
{
var brandTypesList = DbContext.BrandType.Where(p => p.Active == true);
if (brandId != null)
{
brandTypesList = brandTypesList.Where(p => p.BrandId == brandId);
}
return Json(brandTypesList.Select(x => new { BrandTypeId = x.BrandTypeId, BrandTypeName = x.Name }), JsonRequestBehavior.AllowGet);
}
Then we create the JS code to manipulate the HTML at runtime and bind the selected values to the MVC model.
var brandTypeIdDualListbox = new Object();
$(document).ready(function ()
{
//we create the dual list control
brandTypeIdDualListbox = $('select[name="BrandTypeIdList"]').bootstrapDualListbox({
nonSelectedListLabel: 'Non-selected',
selectedListLabel: 'Selected',
preserveSelectionOnMove: 'moved',
moveOnSelect: false,
});
//we setup the change event for the control
$('select[name="BrandTypeIdList').on('change', function (args)
{
//we traverse every option
$("#BrandTypeIdList option").each(function (index,element)
{
//we check if the element has the `data-sortindex` attribute
if (!!$(element).attr('data-sortindex'))
$(element).attr('selected', 'selected');
else
$(element).removeAttr('selected');
});
})
});
function filterBrands()
{
var brandId = $("#BrandId").val();
if (brandId == "")
brandId = "-1";
return {
BrandId: brandId
};
}
function populateBrandTypeIdDualListbox()
{
$.getJSON(urlGetCascadeMultiSelectBrandTypeByBrand, filterBrands(), function (data)
{
var items;
$.each(data, function (i, item)
{
brandTypeIdDualListbox.append("<option value=" + item.BrandTypeId/*Value*/ + ">" + item.BrandTypeName/*Key or Text*/ + "</option>");
});
brandTypeIdDualListbox.trigger('bootstrapDualListbox.refresh', true); // we refresh the control
});
}
function onBrandIdDdlChange(evt)
{
var brandIdDropDownList = $("#BrandId").data("kendoDropDownList");
$('#BrandTypeIdList').empty();
brandTypeIdDualListbox.trigger('bootstrapDualListbox.refresh', true);
if ($("#BrandId").val() == "" || $("#BrandId").val() == "-1")
{
//if no value is selected we disable the control
$(".bootstrap-duallistbox-container").find("*").prop("disabled", true);
}
else
{
populateBrandTypeIdDualListbox();
$(".bootstrap-duallistbox-container").find("*").prop("disabled", false); // we enable the control
}
}
I'm currently using this Wizard in my application.
In one of my steps, I need to add and remove items from a table. Add functions works fine. But I can't make the Delete function work. I've searched SO and other resources online, can't find a solution.
This is what I've so far:
Wizard Step 2 Table:
<table id="LibList" class="table table-responsive table-striped">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Step3.Liabilities[0].Types)
</th>
<th>
#Html.DisplayNameFor(model => model.Step3.Liabilities[0].Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Step3.Liabilities[0].Teams)
</th>
<th>
<label>Delete</label>
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Step3.Liabilities) {
Html.RenderPartial("_LibListItem", item);
}
</tbody>
</table>
Partial View:
<tr>
<td>
#Html.DropDownListFor(model => model.Type, Model.Types, new { #class = "selectpicker form-control", id = string.Format("{0}_{1}", "TYPE", Model.ID) })
</td>
<td>
#Html.TextBoxFor(model => model.Name, new { #class = "form-control", id = string.Format("{0}_{1}", "NAME", Model.ID) })
</td>
<td>
#Html.TextBoxFor(model => model.Teams, new { #class = "form-control", #type = "currency", id = string.Format("{0}_{1}", "TERMS", Model.ID) })
</td>
<td>
#Ajax.ActionLink("Delete", "Delete", "QuestionWizard", new { id = Model.ID },
new AjaxOptions() {
HttpMethod = "Delete",
Confirm = "Are you sure you want to delete this record?",
OnComplete = "function() { $(this).parent().parent().remove() }"
},
new { #class = "btn btn-primary" })
</td>
Add and Delete Action:
public ActionResult AddRow() {
LiabilityModel lib = new LiabilityModel();
try {
if (LiabilitySessionState.Count == 0) {
lib.ID = 1;
} else {
lib.ID = LiabilitySessionState.LastOrDefault().ID + 1;
}
LiabilitySessionState.Add(lib);
return PartialView("_LibListItem", lib);
} catch (Exception ex) {
System.Web.HttpContext.Current.Application.Add("LASTERROR", ex);
return RedirectToAction("Index", "Error");
}
}
public void Delete(int Id) {
try {
if (LiabilitySessionState.Count > 0) {
LiabilitySessionState.RemoveAll(item => item.ID == Id);
}
} catch (Exception ex) {
System.Web.HttpContext.Current.Application.Add("LASTERROR", ex);
RedirectToAction("Index", "Error");
}
}
public List<LiabilityModel> LiabilitySessionState {
get {
if (Session["LiabilityModel"] == null) {
return LiabilitySessionState = new List<LiabilityModel>();
} else {
return Session["LiabilityModel"] as List<LiabilityModel>;
}
}
set {
Session["LiabilityModel"] = value;
}
}
Script:
<script type="text/javascript">
$(document).ready(function () {
$('.add-button').click(function () {
var action = "/QuestionWizard/AddRow";
$.ajax({
url: action,
cache: false,
success: function (result) {
$("#LibList tbody").append($(result));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
})
$(".remove-button").click(function () {
$(this).parents().parent().remove();
return false;
});
});
Right now, the Delete Action returns a blank page, because I'm not returning a view. But, I'm not sure what view to return.
Please help!
Thanks in advance.
Firstly your Delete() method is changing data so it needs to be a POST, not a GET (which #Ajax.ActionLink() is). Next, your 'delete link' does not have class="remove-button" so $(".remove-button").click(function () { wont do anything. Since you already using jquery ajax methods to add items (refer notes below), there seems no point using the Ajax helpers anyway (your just adding extra overhead by loading the jquery.unobtrusive-ajax.js file).
Change the last <td> element of the partial to
<td>
<button type="button" class="remove-button" data-id=#Model.ID>Delete</button>
</td>
Then in the main view, use the following script (note you need event delegation so you can remove dynamically added items)
var url = '#Url.Action("Delete", "YourControllerName")';
$('#LibList').on('click', .remove-button, function() {
var row = $(this).closest('tr');
var id = $(this).data('ID');
if (id) { // assumes property ID is nullable, otherwise may need to test if id != 0
$.post(url, {ID: id }, function(response) {
if(response) {
row.remove();
} else {
// Oops - display message?
}
});
} else {
// its a new row so it has not been saved yet - just delete the row
row.remove();
}
});
and the controller method should look like
[HttpPost]
public JsonResult Delete(int ID)
{
// delete the item
return Json(true); // or if an exception occurred, return(null) to indicate failure
}
Side notes:
Both your AddRow() and Delete() methods include a return
RedirectToAction() statement. You are making ajax calls which stay
on the same page so RedirectToAction() is pointless (it will never
be executed)
If you believe the "Add functions works fine", then you must have
some unnecessary hacks in order to make this work (your generating
duplicate name attributes for the controls (without indexers)
which will not bind to your collection of Liabilities). You need
to generate existing items in a for loop and include a hidden
input for an Index property, and use a client side template to
generate new items; or you need to use the BeginCollectionItem
helper if using a partial view. This
answer
shows how to use both techniques.
You don't appear (and you should not need) to access the id
attributes of the controls in your table. Instead of using id = string.Format("{0}_{1}", "NAME", Model.ID), just use id="" which
will render the element without and id attribute.
Why am I not cleared form ? ModelState.Clear(); is not work! in updated form sends the data again. Tried many different solutions but all in vain, so hope to find here a solution to this problem. Help me please!
"Controller"
public ActionResult Yandex()
{
ViewData["sucsess"]=" ";
return View();
}
[HttpPost]
public ActionResult Yandex(LoginModel model)
{
if (model.option1)
{
md.Modules_Update(1,1);
ViewData["sucsess"] = "• Дані успішно збережені!";
}
else
{
md.Modules_Update(1, 0);
ViewData["sucsess"] = "• Дані успішно збережені!";
}
ModelState.Clear();
return View( );
}
"View"
#using (Html.BeginForm())
{
Settings exit = new Settings();
<span class="property">Модуль включений: </span>
<span class="property">Так</span>
if (exit.Modules(1).ToString() == "1")
{
#Html.RadioButtonFor(m => m.option1, true, new { #checked = "checked", id = "1", #class="radio" })
}
else
{
#Html.RadioButtonFor(m => m.option1, true, new { id = "1", #class="radio" })
}
<span class="property">Ні</span>
if (exit.Modules(1).ToString() == "0")
{
#Html.RadioButtonFor(m => m.option1, false, new { #checked = "checked", id = "0", #class="radio" })
}
else
{
#Html.RadioButtonFor(m => m.option1, false, new { id = "0", #class="radio" })
}
<input type="submit" value="Зберегти" class="save" />
}
<span class="property_col">#ViewData["sucsess"]</span>
Values are still present in the POST request. The proper way to do this is to redirect to your GET action:
[HttpPost]
public ActionResult Yandex(LoginModel model)
{
if (model.option1)
{
md.Modules_Update(1,1);
TempData["sucsess"] = "• Дані успішно збережені!";
}
else
{
md.Modules_Update(1, 0);
TempData["sucsess"] = "• Дані успішно збережені!";
}
return RedirectToAction("Yandex");
}
Also notice that I have used TempData to transport the message during the redirect. So you might need to adapt your view accordingly:
<span class="property_col">#TempData["sucsess"]</span>
How can i get this work in MVC Telerik Grid Control
columns.Template(e =>
{
if (e.EndDate>DateTime.Now )
{
#Html.ActionLink("Stop", "StopMedication", "Medication",
new { id = e.PrescriptionID }, new { #class = "standard button" })
}
else {
#Html.ActionLink("Renew", "RenewMedication", "Medication",
new { id = e.PrescriptionID }, new { #class = "standard button" })
}
});
The following snippet should work perfectly fine in the Telerik Grid template column using Razor syntax:
columns.Template(
#<text>
#if (#item.EndDate > DateTime.Now)
{
#Html.ActionLink("Stop", "StopMedication", "Medication",
new { id = #item.PrescriptionID }, new { #class = "standard button" })
}
else
{
#Html.ActionLink("Renew", "RenewMedication", "Medication",
new { id = #item.PrescriptionID }, new { #class = "standard button" })
}
</text>
);
Taking use of the #<text></text> inside of the template, as well as using the #item object, which represents the current item (entity tied to the row) and it's properties, will allow you to have this template up and running.