I think this is a really simple question which for some reason i cannot think of how to do!
I have a view with the following:
<li>
<label>Job Title</label>
<%= Html.TextBox("JobTitle",Model.Person.JobTitle, new { type = "text", required = "required", placeholder = "Required" } ) %>
<%= Html.ValidationMessage("JobTitle","") %>
</li>
On submit if the field is not filled out a pop up "Please fill in this field" appears.
I want to customise this message to be "Please enter your job title"
I thought i would just need to change the Person.cs to:
/// <summary>
/// JobTitle
/// </summary>
[Required(ErrorMessage = "Please enter your Job Title")]
[StringLength(128, ErrorMessage = "JoBTitle maximum length is 128")]
public String JobTitle { get; set; }
but i can t think for the life of me what to do sorry!
ok not sure if thsi is the best way to do this - probably not!! but this works so...
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function (e) {
var currentId = $(this).attr('id');
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
if (currentId == "JobTitle") {
e.target.setCustomValidity("Please enter your Job Title");
}
if (currentId == "FirstName") {
e.target.setCustomValidity("Please enter your First Name");
}
}
};
elements[i].oninput = function (e) {
e.target.setCustomValidity("");
};
}
})
//]]>
</script>
Related
I want to pass selected Drop down list value to Ajax Action Link which is I am using in Controller. Every time When I will change drop down list value. I want that respective value pass to the action link.
What I need to write here in Ajax Action Link ????
Drop Down List
<div class="form-group">
#Html.DropDownListFor(model => model.ComponentId, ((List<string>)ViewBag.Cdll).Select(model => new SelectListItem { Text = model, Value = model }), " -----Select Id----- ", new { onchange = "Action(this.value);", #class = "form-control" })
</div>
Ajax Action Link
<div data-toggle="collapse">
#Ajax.ActionLink("Accessory List", "_AccessoryList", new { ComponentId = ???? }, new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "divacc",
InsertionMode = InsertionMode.Replace
})
</div>
Controller
public PartialViewResult _AccessoryList(string ComponentId)
{
List<ComponentModule> li = new List<ComponentModule>();
// Code
return PartialView("_AccessoryList", li);
}
Here is a new post. I do dropdowns a little different than you, so I am showing you how I do it. When you ask what to pass, I am showing you how to pass the dropdown for 'component' being passed. I also show how to pass from ajax back to the page.
Controller/Model:
//You can put this in a model folder
public class ViewModel
{
public ViewModel()
{
ComponentList = new List<SelectListItem>();
SelectListItem sli = new SelectListItem { Text = "component1", Value = "1" };
SelectListItem sli2 = new SelectListItem { Text = "component2", Value = "2" };
ComponentList.Add(sli);
ComponentList.Add(sli2);
}
public List<SelectListItem> ComponentList { get; set; }
public int ComponentId { get; set; }
}
public class PassDDLView
{
public string ddlValue { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public ActionResult PostDDL(PassDDLView passDDLView)
{
//put a breakpoint here to see the ddl value in passDDLView
ViewModel vm = new ViewModel();
return Json(new
{
Component = "AComponent"
}
, #"application/json");
}
public ActionResult IndexValid8()
{
ViewModel vm = new ViewModel();
return View(vm);
}
View:
#model Testy20161006.Controllers.ViewModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexValid8</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnClick").click(function () {
var PassDDLView = { ddlValue: $("#passThis").val() };
$.ajax({
url: '#Url.Action("PostDDL")',
type: 'POST',
data: PassDDLView,
success: function (result) {
alert(result.Component);
},
error: function (result) {
alert('Error');
}
});
})
})
</script>
</head>
<body>
<div class="form-group">
#Html.DropDownListFor(m => m.ComponentId,
new SelectList(Model.ComponentList, "Value", "Text"), new { id = "passThis" })
<input type="button" id="btnClick" value="submitToAjax" />
</div>
</body>
</html>
I am beginner in MVC and Ajax development and want a like button in my web, which should work like this: if the user clicks on it total likes will be incremented by 1 and if the user clicks it again (dislike) then it will decremented by 1. What I have done so far is this:
Here's the Model:
public class Like
{
public int Id { get; set; }
public virtual Video Video { get; set; }
public int VideoID { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
Here is the Controller:
Post Method
[HttpPost]
public ActionResult Like(int Id, Like like)
{
if (ModelState.IsValid && User.Identity.IsAuthenticated == true)
{
like.Video = storeDB.Videos.Find(Id);
like.UserId = User.Identity.GetUserId();
var userlike = storeDB.Likes.Where(l => l.UserId == like.UserId && l.VideoID == Id);
if (userlike.Count() == 0)
{
storeDB.Likes.Add(like);
storeDB.SaveChanges();
}
else if (userlike.Count() == 1)
{
var likeDel = storeDB.Likes.FirstOrDefault(l => l.UserId == like.UserId && l.VideoID == Id);
storeDB.Likes.Remove(likeDel);
storeDB.SaveChanges();
}
List<Like> videoLikes = storeDB.Likes.Where(v => v.VideoID == Id).ToList();
int nooflikes = videoLikes.Count();
ViewBag.noLikes = nooflikes;
return Json(ViewBag.noLikes, JsonRequestBehavior.AllowGet);
}
else
{
ViewBag.Message = "Login to like this video";
return PartialView("Like", ViewBag.noLikes);
}
This is the Get method of Like:
public ActionResult Like(int id)
{
List<Like> videoLikes = storeDB.Likes.Where(v => v.VideoID == id).ToList();
int nooflikes = videoLikes.Count();
ViewBag.noLikes = nooflikes;
return Json(ViewBag.noLikes, JsonRequestBehavior.AllowGet);
}
and I have created a Partial View for this:
#if (ViewBag.Message != null)
{
<script>
$(document).ready(function () {
alert('#ViewBag.Message');
});
</script>
}
//to display total likes
<input type="text" id="likes" name="likes" value='#ViewBag.noLikes' readonly="readonly" style="border:none; background-color:transparent; width:20px" /><span style="color:black">likes</span>
and this is the main view in which I am using Ajax.BeginForm()
#using (Ajax.BeginForm("Like", "VOD", new { Id = Model.Id },
new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "likecount"
}))
{
<button type="submit" id="like" value="Like" class=" btn btn-primary btn-xs"> Like <span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span> </button>
}
<span id="likecount">
#Html.Partial("Like", new Models.Like())
</span>
Now the issue is that when the page is first loaded it is not displaying total likes, and when I click on like button it returns 1 and when I click like button again it returns 0 but when I refresh the page or when I post back to another page total likes again disappear.
Can anybody help me?
Instead of doing so much code you can do above functionality in simple way.
You will required following to do so,
2 Action Methods,
1. Increment Like Count.
2. Decrease Like Count.
2 Buttons on web page
1. Like Button (Initially visible)
2. DisLike Button (Initially Invisible)
you can create a ajax request on both buttons something like bellow,
$("#btnLike").click(function () {
$.ajax({
type: "POST",
url: "Controller/LikeAction",
data: { /* Your Data */ };
success: function (result) {
// Hide Like Button & Show Dislike Button
},
error: function (error) {
alert("error = " + error);
}
});
});
Same way you can create ajax request for dislike button also. You just need to hide and show buttons.
I am using #Ajax.Beginform in my View which is tightly bound to the ViewModel.
I've #Html.ListBoxFor inside my form. I add and delete items from the listbox using jQuery. Now what I am want to achieve is that onpress of the submit button, it should send full data present in the listbox regardless of which are selected. Currently it sends the list to controller if I select all the item in the listbox and press submit button. But I don't want to do that. Any idea as to how to achieve this?
Can it be sent as a form parameter.
#using (Ajax.BeginForm("SaveTextComponent", "LoanFilterEditor", new{ param1 = Model.listBoxItem}, new AjaxOptions { HttpMethod = "POST", OnSuccess = "SUCCESS" }))
I try to accept the parameter in the controller like this
public ActionResult SaveTextComponent(TextComponentViewModel model, List<SelectListItem> list)
{
}
But list is null.. Please help.
Maybe you can use this javascript to select all items at your listbox and then, send it to controller:
function listbox_selectall(listID, isSelect) {
var listbox = document.getElementById(listID);
for(var count=0; count < listbox.options.length; count++) {
listbox.options[count].selected = isSelect;
}
}
And after that, you can call the function on your form in this way:
<script>
function submit() {
listbox_selectall('righthand_side_listbox_id', true);
return true;
}
</script>
<form onsubmit="return submit()">
...
</form>
Credits to Viral Patel blog
You can follow my example:
Model:
pulic class TextComponentViewModel {
public int[] SelectedListItem { get; set; }
public List<Item> ListItem { get; set; }
}
public class Item {
public int Id { get; set; }
public String Name { get; set; }
}
View:
#model TextComponentViewModel
#using (Ajax.BeginForm("SaveTextComponent", "LoanFilterEditor", null, new AjaxOptions { HttpMethod = "POST", OnSuccess = "SUCCESS" }, new {name = "mainForm", id = "mainForm"}))
{
#Html.ListBoxFor(model => model.SelectedListItem , new MultiSelectList(Model.ListItem, "ID", "Name"))
for(var i = 0; i < Model.ListItem.Count();i++ )
{
#Html.HiddenFor(m => m.ListItem[i].Id)
#Html.HiddenFor(m => m.ListItem[i].Name)
}
<input type = "submit" id="submitButton" />
}
Controller:
public ActionResult SaveTextComponent(TextComponentViewModel model)
{
}
Script:
$("#submitButton").click(function(){
$("#mainForm").submit();
});
I came upon the strangest situation so far. I have a form that has two textboxes. I also have buttons that belong to three different classes such as .addTopTenFav , .addCurrentFav , .addOther. I have added validation logic and attributes to my Entity model, and it works as expected for two of my buttons. That is when I click a particular button I do something like myform.validate().Form(); and then I check if ($("#myform").valid()) so in two of my poartial views the form is validated, no error messages appear and it's all good. BUT for some strange reason when I click the .addOtherSong button the if statement that checks if my form is valid goes to the else part where i put a simple alert box. No error messages appear, i double check what i type into the textboxes... and of course... somehow the form is not valid while clicking the other buttons the form is valid.
But there's more, so i try to debug this, in google's chrome browser I use the console and i type in something like $("#myform").validate().element( "#myselect" ); to check each textbox one by one, and it returns true for both of them meaning that my input is validated and passes the test, but when I run the app and I click on my add button the form is not Valid, what is wrong?
$(function () {
$(document).on("click", ".btnAddSongTilesToGenre", function (e) {
var name = $('#youTubeNameTxt').val();
var link = $('#youTubeLinkTxt').val();
var len = link.length;
var substr = link.substr(31, len - 31);
var container = $(this).parent().parent().find(".actualTilesContainer");
$(container).slideDown();
var genreId = $(this).attr("name");
$("#hiddenRank").val(genreId);
$("#AddTopTenFavForm").validate().form();
if ($("#AddTopTenFavForm").valid()) {
$.ajax({
beforeSend: function () { ShowAjaxLoader(); },
url: "/Home/AddSong",
type: "POST",
data: $("#AddTopTenFavForm").serialize(),
success: function (data) { HideAjaxLoader(), ShowMsg("Song Added Successfully"), $(container).find('ul').append('<li><a class="savedLinks" href="#" name="' + substr + '" >' + name + '</a> <span name= ' + data + ' class="btnDeleteSong dontDoAnything">x</span></li>'); },
error: function () { HideAjaxLoader(), ShowMsg("Song could not be added, please try again") }
});
$('#youTubeLinkTxt').val('');
$('#youTubeNameTxt').val('');
}
else {
alert("notValid");
}
if ($(e.target).hasClass("dontDoAnything")) {
e.stopPropagation();
return false;
}
});
$("#otherFavContainer").on("click", ".songTilesGenreContainer", function (e) {
var myVar = $(this).find(".actualTilesContainer");
if ($(myVar).hasClass("minimalized")) {
$(myVar).removeClass("minimalized").addClass("maximized").slideDown();
}
else {
$(myVar).removeClass("maximized").addClass("minimalized").slideUp();
}
});
my validation attributes
namespace yplaylist.Models
{
[MetadataType(typeof(TopTenFav_Validation))]
public partial class TopTenFav
{
}
public class TopTenFav_Validation
{
[RegularExpression("http://www.youtube.com/watch\\?v=.*", ErrorMessage = "Youtube Link must begin with: http://www.youtube.com/watch?v= ")]
[Required(ErrorMessage = "Youtube link is Required")]
[StringLength(100, ErrorMessage = "Song Title cannot exceed 100 characters")]
public string YoutubeLink { get; set; }
[StringLength(100, ErrorMessage = "Youtube link cannot exceed 100 characters")]
[Required(ErrorMessage = "Song title is Required")]
public string Title { get; set; }
}
}
In my MVC application I am using an ajax dropdownlist and an ajax Cascading dropdownlist I want to write the onChange event of the cascading dropdownlist please tell me what shall I do.
I am posting the view page that I am using and the js file that creates the cascading dropdownlist.Please tell me where all the places I need to do the changes.
The view Page is as follows
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index1</title>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script type="text/javascript" src="../../Scripts/MicrosoftMvcAjax.js"></script>
<script type="text/javascript" src="../../Scripts/CascadingDropDownList.js"></script>
</head>
<body>
<div>
<label for="Makes">Car Make:</label>
<%= Html.DropDownList("Makes")%>
<label for="Makes">Car Model:</label>
<%= Html.CascadingDropDownList("Models", "Makes")%>
<br />
<%=Html.TextBox ("id",ViewData ["id"]) %>
</div>
</body>
</html>
The javascript where the cascading dropdown list is being formed:
public static class JavaScriptExtensions
{
public static string CascadingDropDownList(this HtmlHelper helper, string name, string associatedDropDownList)
{
var sb = new StringBuilder();
// render select tag
sb.AppendFormat("<select name='{0}' id='{0}'></select>", name);
sb.AppendLine();
// render data array
sb.AppendLine("<script type='text/javascript'>");
var data = (CascadingSelectList)helper.ViewDataContainer.ViewData[name];
var listItems = data.GetListItems();
var colArray = new List<string>();
foreach (var item in listItems)
colArray.Add(String.Format("{{key:'{0}',value:'{1}',text:'{2}'}}", item.Key, item.Value, item.Text));
var jsArray = String.Join(",", colArray.ToArray());
sb.AppendFormat("$get('{0}').allOptions=[{1}];", name, jsArray);
sb.AppendLine();
sb.AppendFormat("$addHandler($get('{0}'), 'change', Function.createCallback(bindDropDownList, $get('{1}')));", associatedDropDownList, name);
sb.AppendLine();
sb.AppendLine("</script>");
return sb.ToString();
}
}
public class CascadingSelectList
{
private IEnumerable _items;
private string _dataKeyField;
private string _dataValueField;
private string _dataTextField;
public CascadingSelectList(IEnumerable items, string dataKeyField, string dataValueField, string dataTextField)
{
_items = items;
_dataKeyField = dataKeyField;
_dataValueField = dataValueField;
_dataTextField = dataTextField;
}
public List<CascadingListItem> GetListItems()
{
var listItems = new List<CascadingListItem>();
foreach (var item in _items)
{
var key = DataBinder.GetPropertyValue(item, _dataKeyField).ToString();
var value = DataBinder.GetPropertyValue(item, _dataValueField).ToString();
var text = DataBinder.GetPropertyValue(item, _dataTextField).ToString();
listItems.Add(new CascadingListItem(key, value, text));
}
return listItems;
}
}
public class CascadingListItem
{
public CascadingListItem(string key, string value, string text)
{
this.Key = key;
this.Value = value;
this.Text = text;
}
public string Key { get; set; }
public string Value { get; set; }
public string Text { get; set; }
}
You should register the control during the application initialization. It's what you have to render in the page via CascadingDropDownList extension method.
Sys.Application.add_init(function() {
$create(NameSpace.ClassName, null, null, null, $get("id"));
});
Type.registerNamespace("NameSpace");
NameSpace.ClassName = function(element) {
NameSpace.ClassName.initializeBase(this, [element]);
}
NameSpace.ClassName.prototype = {
initialize: function() {
NameSpace.ClassName.callBaseMethod(this, "initialize");
$addHandler(this.get_element(), "change", Function.createDelegate(this, onChange));
},
dispose: function() {
NameSpace.ClassName.callBaseMethod(this, "dispose");
$removeHandler(this.get_element(), "change", Function.createDelegate(this, onChange));
},
onChange: function() {
// Do somethings...
}
}
NameSpace.ClassName.registerClass(NameSpace.ClassName, Sys.UI.Control);
The above code snippet illustrates how to add an handler for change event.