Client-side validation on chosen select dropdownlist - asp.net-mvc-5

I am using asp.net mvc 5. I am working on client-side validation on chosen- dropdown list.
I am facing a problem with required validation. Validation is working fine on button click but when I select the item, validation error message should be removed automatically and when I deselect the item,it should be display validation error message.
This is Model
[Required(ErrorMessage = "Gender is required.")]
public string Gender { get; set; }
This is View
#Html.DropDownListFor(m => m.Gender, new List<SelectListItem>
{ new SelectListItem{Text="Male", Value="M"},
new SelectListItem{Text="Female", Value="F"}}, "Plz Selecct..." , new { #class = "chosen-select"})
#Html.ValidationMessageFor(m => m.Gender, "", new { #class = "error" })
Plaese any input on this it will be appreciable.
Thanks.

Related

#html.dropdown onchange event MVC5

I have a View with a dropdownlist. I would like to select a value from the dropdownlist and depending on that value pull into the View a form related to that selection.
Looks like this:
I would like the form to appear below this ddlist and if the user changes the value in the ddlist, it would change the form.
Here's my "Add" View:
<div id="matSelContainer">
#Html.Action("SelectMaterial", "Materials", "Materials")
</div>
Here's the "SelectMaterial" View:
#model Procurement.Models.Material.MaterialType
#Html.Label("Select a Material Type: ")
#Html.DropDownListFor(
x => x.MaterialTypeList,
new SelectList(Model.MaterialTypeList, "MaterialTypeId", "Name")
)
Here's my Controller:
public ActionResult Add()
{
return View();
}
public ActionResult SelectMaterial()
{
materialTypes.LoadMaterialTypes();
return PartialView(materialTypes);
}
I would like to have a separate View for each Material Type and just call that View based on the selection in the ddlist.
Can someone show me how to achieve this?
Would I add a separate #Html.Action to the "Add" View and then in the Controller have another action return a PartialView?
But how to connect this with the Onchange event?
Update<<
Here's what is almost working for me:
"SelectMaterial" View:
#model Procurement.Models.Material.MaterialType
#Html.Label("Select a Material Type: ")
#Html.DropDownListFor(
x => x.MaterialTypeList,
new SelectList(Model.MaterialTypeList, "MaterialTypeId", "Name"),
new { #onchange="CallChangefunc(this.value)" })
<script>
function CallChangefunc(val) {
//alert("i am a " + obj.options[obj.selectedIndex].text);
//alert(obj.options[obj.selectedIndex].text);
window.location.href = "/Materials/MyMethod/" + val;
}
</script>
In my Controller I have this ActionResult:
public ActionResult MyMethod(string value)
{
return PartialView();
}
My controller is getting called when I change selection but the value coming in is null. I can see on the browser address bar that the expected selected value is being passed. Why is it null in controller? (I tried adding an [HttpPost] to ActionResult with no luck.)

Issue of creating new item using PXAction in Acumatica

I encounter an issue when using PXAction to create new item in Acumatica and appreciate you can give me a help.
I added the custom auto-increment attribute for the "DocumentNbr" field in my "Document" DAC following the Acumatica official document's example "Example 8.2: Creating the Custom AutoNumber Attribute" in the T200 Document as below.
Here is the snippet of code of the attribute setting for the "DocumentNbr" field:
#region DocumentNbr
protected string _DocumentNbr;
[PXDBString(15, IsUnicode = true, IsKey = true, InputMask = ">CCCCCCCC")]
[PXSelector(typeof(Search<MABUIPDocument.documentNbr>),
typeof(MABUIPDocument.documentNbr),
typeof(MABUIPDocument.documentDate),
typeof(MABUIPDocument.status),
typeof(MABUIPDocument.vendorID)
)]
[AutoNumber(typeof(MABUIPSetup.autoDocumentNbr), typeof(MABUIPSetup.lastDocumentNbr))]
[PXDefault()]
[PXUIField(DisplayName = "ID")]
public string DocumentNbr
{
get
{
return this._DocumentNbr;
}
set { this._DocumentNbr = value; }
}
public class documentNbr : IBqlField { }
#endregion
It is working fine that I can add, edit and delete documents normally as below:
I have a requirement that creates a new item when clicking button, so I created the "Test Creating new item" button including creating new item logic as below, in my understanding, it would show the created item after clicked the "Test Creating new item" button.
public PXAction<MABUIPDocument> BtnCreatingNew;
[PXButton(CommitChanges = true)]
[PXUIField(DisplayName = "Test Creating new item", Visible = true)]
protected virtual void btnCreatingNew()
{
MABUIPDocument row = Documents.Current;
row.DocumentDesc = "Test" + DateTime.Now.ToString();
row = Documents.Update(row);
Actions.PressSave();
}
The actually circumstance is although the new row has been inserted into the database and will occur if I click the "Next" arrow but the form content of the current view is cleared after clicking the button, I tried many methods like setting "Document.Current = row" and "sender.SetValue(row, fieldName, fieldNewValue)" but the content has been keeping blank after clicking the button whatever I tried. Can you please give me a hint what possible reason caused the issue? Thank you very much!
Because your ID value is only generated while new document is saved in the database, you must accordingly update PXAdapter's Searches collection with the actual ID value saved in the database:
public PXAction<MABUIPDocument> BtnCreatingNew;
[PXButton(CommitChanges = true)]
[PXUIField(DisplayName = "Test Creating new item", Visible = true)]
protected virtual IEnumerable btnCreatingNew(PXAdapter adapter)
{
MABUIPDocument row = Documents.Current;
row.DocumentDesc = "Test" + DateTime.Now.ToString();
row = Documents.Update(row);
Actions.PressSave();
adapter.Searches[adapter.Searches.Length - 1] = row.DocumentNbr;
return adapter.Get();
}

How Using tempdata to pass data entered by user in a data field from view to another view

I am new to MVC. I one please help me on how to assign value entered by user (for instance table column such as username) in a view to TempData.
I also want to pass the assigned data to a column in another view
In your view, add a form field:
<input name="myfield" type="text" />
In your controller's action, get the field and store it in TempData:
public ActionResult ProcessIt(string myfield)
{
TempData["yourkey"] = myfield;
return RedirectToAction("SomeOtherAction");
}
Now you can use it in the SomeOtherAction view:
<div>Entered data: #TempData["yourkey"]</div>
Thanks, I am creating web test, the controller for the question
public async Task Create([Bind(Include = "QuestionID,Question")]
TestQuestion testQuestion, string command, FormCollection QuestionData)
{
if (ModelState.IsValid)
{
db.TestQuestions.Add(testQuestion);
await db.SaveChangesAsync();
return RedirectToAction("Create", "TestOptions");
}
The controller for the options:
public async Task Create([Bind(Include = "OptionID,QuestionID,OptionA")] TestOption testOption)
{
if (ModelState.IsValid)
{
db.TestOptions.Add(testOption);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.QuestionID = new SelectList(db.TestQuestions, "", "", testOption.QuestionID);
return View(testOption);
}
I desire to display the question just entered by the user in the Create method of the option controller so that the user would enter the options for question.
The program create a dropdownlist of all the questions l've enter before, but I want only the last question should show in the redirected view.

Why is my default value for DropDownListFor not working properly?

For whatever reason, my default value for my Html.DropDownListFor isn't working:
#Html.DropDownListFor(model => model.DomainList,
new SelectList(Model.DomainList, "DomainId", "Name", Model.SingleDomain.DomainId),
new { #class = "form-control" })
Any idea why?
UPDATE
With the answer below, I updated my code to the following:
#Html.DropDownListFor(model => model.SelectedDomain,
new SelectList(Model.DomainList, "DomainId", "Name", Model.SelectedDomain),
"Select a Domain",
new { #class = "form-control" })
Try this:
In your ViewModel, add an integer to store the selected domain id:
public int SelectedDomainId { get; set; }
Change your DropDownListFor to:
#Html.DropDownListFor(model => model.SelectedDomainId,
new SelectList(Model.DomainList, "DomainId", "Name", Model.SingleDomain.DomainId),
new { #class = "form-control" })
Now on your post-back the selected id will be posted in SelectedDomainId.
Or, you could add the single domain object to your VM (to indicate which one was selected):
public Domain SelectedDomain { get; set; }
And change your DropDownListFor to:
#Html.DropDownListFor(model => model.SelectedDomain,
new SelectList(Model.DomainList, "DomainId", "Name", Model.SingleDomain.DomainId),
new { #class = "form-control" })
I usually use the selected ID, but I think either should work
Here is another good example:
MVC3 DropDownListFor - a simple example?
If someone is having trouble with Html.DropdownList keep in mind that
#Html.DropDownList("Country", ViewBag.Country as List<SelectListItem>) --> doesn't select the default value
#Html.DropDownList("Countries", ViewBag.Country as List<SelectListItem>) --> selects the default value
For more details, see: http://www.binaryintellect.net/articles/69395e7d-7c7c-4318-97f5-4ea108a0da97.aspx
my problem solved when change viewbag.xxxxxxx to
viewbag.xxxxxxx1 issue was hapend when model propety and viewbag property was same.
controller :
ViewBag.serviceid = new SelectList(db.services.ToList(), "id", "titel", package.service_id);
view:
#Html.DropDownListFor(Model => Model.service_id, ViewBag.serviceid as SelectList, htmlAttributes: new { #class = "form-control" })

open a MVC4 view inside a jquery Dialog

I want to take a view and instead of opening a new page I want to just open that view inside a Jquery dialog. I was just wondering how it's done or if possible.
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Jquery_Dialog.Models;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
namespace Jquery_Dialog.Controllers
{
public class HomeController : Controller
{
private IEnumerable<Product> Products
{
get
{
return new List<Product>
{
new Product {ProductID = 1, Name = "Train", Category = "Toy", Price = 29.99M},
new Product {ProductID = 2, Name = "Truck", Category = "Toy", Price = 19.99M},
new Product {ProductID = 3, Name = "Bread", Category = "Food", Price = 2.49M},
new Product {ProductID = 4, Name = "Cookies", Category = "Food", Price = 2.99M}
};
}
}
public ActionResult Index()
{
IEnumerable<Product> productList = Products;
return View(productList);
}
public ActionResult Details(int id)
{
Product model = Products.Where(p => p.ProductID == id).SingleOrDefault();
return Request.IsAjaxRequest() ? PartialView(model) : PartialView(model);
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
Index.cshtml
#model IEnumerable<Jquery_Dialog.Models.Product>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css " />
<script src="http://code.jquery.com/jquery-1.8.2.js "></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js "></script>
<table> #foreach (var item in Model) {
<tr>
<td>
#Html.ActionLink(item.Name, "Details", new { id = item.ProductID }, new { #class = "ajax-details" })
</td>
</tr>
}
</table>
<div id="dialog" title="Title of dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
<script>
$(function () {
$('.ajax-details').on('click', function (e) { // bind to click event
// go get the page using the link's `href`
$.get($(this).prop('href'), function (response) {
$(response).dialog(); // take the response and throw it up in a dialog
// optional: Use jQuery UI's options to specify buttons and other
// settings here as well. It's also probably a good idea to
// bind the close event and $().remove() this element from
// the page on close since the user can click links over and
// over. (prevent DOM overload of hidden elements)
});
e.preventDefault(); // don't let it continue on
});
});
</script>
<script>
$("#dialog").dialog();
</script>
As you can see I have a simple dialog that opens a div but I want to be able to open the details view instead of clicking the ActionLink and going to a different page, I want to be able to click the ActionLink and have it open up in the dialog.
Assuming you make the ActionLink a little more accessible (by using a class name for instance):
#Html.ActionLink(item.Name, "Details", new { id = item.ProductID },
/* htmlAttributes: */ new { #class = "ajax-details" })
You also make a modification to the action so we can fetch partial contents when it's an ajax request:
public ActionResult Details(int id)
{
// this is another way of making sure that AJAX calls get partial content,
// but a normal visit would render the entire page.
return Request.IsAjaxRequest() ? PartialView(model) : View(model);
}
Optional You could also adjust your _ViewStart.cshtml file to do the same if this was common place on the website to render partial views/ajax supplementing:
#{
Layout = IsAjax ? null : "~/Views/Shared/_Layout.cshtml";
}
Now, we wire it up with AJAX. Again, reference the class name we game the link earlier (ajax-details):
$('.ajax-details').on('click',function(e){ // bind to click event
// go get the page using the link's `href`
$.get($(this).prop('href'), function(response){
$(response).dialog(); // take the response and throw it up in a dialog
// optional: Use jQuery UI's options to specify buttons and other
// settings here as well. It's also probably a good idea to
// bind the close event and $().remove() this element from
// the page on close since the user can click links over and
// over. (prevent DOM overload of hidden elements)
});
e.preventDefault(); // don't let it continue on
});
Don't have the opportunity to test it, but should get you in the ball park. if it doesn't get you close enough, let me know and I'll revisit the answer and adjust.

Resources