I have three divs like this:
<div onclick="GoToContactPage()">
#*Some Code*#
</div>
<div onclick="GoToContactPage()">
#*Some Code*#
</div>
<div onclick="GoToContactPage()">
#*Some Code*#
</div>
on the GotoContactPage() function I only have a redirect link to another view like that
function GoToContactPage() {
window.location.href = '/Home/SecondView';
}
and in that /SecondView I have an input method like that:
<div class="col-md-5">
#Html.TextBoxFor(m => m.Name, new { placeholder = "Name", #class = "form-control", #id= "name"})
</div>
All I was trying to do, when the user choose the first div a specific text appears in the input method in the other view, and so to the another two divs. I was thinking about sending an int then having an if statements and also was thinking about sending the string itself in the OnClick function but don't know what to do? and which is better? What should I do, Please?
You should pass an id in GoToContactPage(id) so that function takes an argument an run according to it.
function GoToContactPage(id) {
if(id== ""){
//your conditions
}else if(id ==""){
//your conditions
}else{
//your conditions
}
}
To get data in Second page pass it through the url www.example.com?id=1&name=xyz and get them on second page by $_GET method.
Related
I'm very new to MVC and Javascript so please be patient with me, I'm working on small application and I came to part when I need to select something from dropdown list and based on that selection I need to redirect user to another View, I also need to determine somehow where I should redirect user, so that is reason why I tried to pass parameter also ( database ID to my post method) but unfortunatelly this is not working, in section below I will post my code:
Method which is sending data to my DropDownList :
public ActionResult ShowArticleGroup()
{
List<ArticleGroup> articlesGroups = GroupsController.GetAllGroups();
ViewBag.articlesGroups = articlesGroups;
return View(articlesGroups);
}
[HttpPost]
public ActionResult ShowArticleGroup(string id)
{
//Here I wanted to take ID of selected Group and because there will be allways 3 Groups I can do if else and Redirect by ID
if(id =="00000000-0000-0000-0000-000000000002")
{
return RedirectToAction("Create","Article");
}
return RedirectToAction("Create", "Article");
}
And my VIEW - there is only one control on the view : just one dropdown, and based on selection I should be redirected to another view, and I wanted here to take ID of selected group and by that I wanted to redirect user to appropiate view:
#model IEnumerable<Model.ArticleGroup>
#{
ViewBag.Title = "Add new article";
}
<h3 style="text-align:center">Choose article group</h3>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
<div class="form-group" style="text-align:center">
#Html.DropDownList("Group", new SelectList(ViewBag.articlesGroups, "GroupID", "GroupTitle.Name"), null, new { onchange = "document.location.href = '/Articles/ShowArticleGroup/' + this.options[this.selectedIndex].value;" })
</div>
</div>
}
First of all, usage of location.href on DropDownList seems wrong here:
#Html.DropDownList("Group", new SelectList(ViewBag.articlesGroups, "GroupID", "GroupTitle.Name"), null,
new { onchange = "document.location.href = '/Articles/ShowArticleGroup/' + this.options[this.selectedIndex].value;" })
AFAIK, location.href used for redirect to another page using HTTP GET, hence it will try to call first ShowArticleGroup action method without parameter, and the URL parameter simply ignored since given URL parameter only exist in POST.
To submit the form with DropDownList, you need to handle change event triggering POST into controller action method:
jQuery
<script type="text/javascript">
$(document).ready(function() {
$("#Group").change(function() {
var groupId = $("#Group").val();
$.post('#Url.Action("ShowArticleGroup", "ControllerName")', { id: groupId }, function (response, status) {
// response handling (optional)
});
});
});
</script>
DropDownList
#Html.DropDownList("Group", new SelectList(ViewBag.articlesGroups, "GroupID", "GroupTitle.Name"), null)
I recommend you using strongly-typed DropDownListFor with binding to a viewmodel approach if you want to pass viewmodel contents during form submit.
NB: $.post is shorthand version of $.ajax which uses POST submit method as default.
Related issues:
Autopost back in mvc drop down list
MVC 4 postback on Dropdownlist change
Below is my code where the i get data from 2 viewbags. one viewbag has the property lists and the other one is a dropdown. how do i get the property list and its corresponding value in the javascipt.
asp.mvc razor view code:
#if (ViewBag.ddlcolmapping != null && ViewBag.excelheaders != null)
{
foreach (var proplists in ViewBag.ddlcolmapping)
{
<div>
<a data-id='#proplists' id='ColumnSelect_#(proplists)' href="#" class="select-categories">#proplists</a>
#Html.DropDownList("ddl", new SelectList(ViewBag.excelheaders), new { #id = #proplists })
<br/><br/>
</div>
}
}
Javascript code
function SaveMapping(elem) {
debugger;
...
}
}
I can offer a solution using JQuery. I'd give some class name to the outer div something like
<div class="someDiv">
<a data-id='#proplists' id='ColumnSelect_#(proplists)' href="#" class="select-categories">#proplists</a>
#Html.DropDownList("ddl", new SelectList(ViewBag.excelheaders), new { #id = #proplists })
<br/><br/>
</div>
And then in the javascript using JQuery, you can do call the following code on some click or any event that you are using to capture the anchor tag text and the selected value from the dropdown. I have thrown some alert to show you how you can pull the value.
$("div.someDiv").each(function () {
alert($(this).find('a').text());
alert($(this).find('select>option:selected').text());
})
I have a customized Django wizard_form.html which shows the user 3 different images on three different pages of my survey.
I am trying to use the below script to update 3 hidden form fields on 3 different pages with the contents of value="{{display_image}}" as a way of storing the filename of the images shown to the user in the Database
This works fine for the first page/image e.g.
<input id="id_9-slider_one_image" name="9-slider_one_image" type="hidden" value="P1D1.jpg"/>
But I cant seem to get it working on the second or third
<input id="id_10-slider_two_image" name="10-slider_two_image" type="hidden" />
Can anyone tell me what I am doing wrong?
My Code
{% if wizard.steps.current in steps %}
<div class="image_rating">
<img src="{% static "survey/images/pathone/" %}{{display_image}}"
value="{{display_image}}" onload="updateInput1(this); updateInput2(this); updateInput3(this);"/>
</div>
<script type="text/javascript">
function updateInput1(ish) {
var valueAttribute = ish.getAttribute("value");
document.getElementById("id_9-slider_one_image").setAttribute(
"value", valueAttribute);
}
function updateInput2(ish) {
var valueAttribute = ish.getAttribute("value");
document.getElementById("id_10-slider_two_image").setAttribute(
"value", valueAttribute);
}
function updateInput3(ish) {
var valueAttribute = ish.getAttribute("value");
document.getElementById("id_11-slider_three_image").setAttribute(
"value", valueAttribute);
}
</script>
Any helps is as always, much appreciated, Thanks.
First, you need to assign the value of the input id to a variable, say element_id
element_id = "id-slider_one_image"
If you can't name them all the same, just give this the actual element ID (e.g.: id_9-slider_one_image).
Then, you need to change the function arguments to also take the element id
function updateInput(ish, elementId) {
var valueAttribute = ish.getAttribute("value");
document.getElementById(elementId).setAttribute(
"value", valueAttribute);
}
Then, your onload attribute needs to pass the element_id string in addition to the element reference:
onload="updateInput(this, '{{element_id}}');"
simply create a function which calls all 3 update functions with try catch
function Update(sender){
try{
updateInput1(sender); }
catch(e){
try{
updateInput2(sender); }
catch(e){
updateInput3(sender);}}
}
and use onload='Update(this)'
So I built this nice MVC 4 web app, I initially stayed away from fancy CSS and JS and just focused on getting it to work. I got to work, then I decide lets add bootstrap too it make it look pretty. Now I would like to add some basic java script. Some stuff like:
<button class="btn btn-default" type="button" onclick="javascript:document.getElementById('elementid').value=0;">Remove</button>
I have a List of parts, a part as a quantity, a number and name. So I loop through the list.
#foreach (Hardware hw in Model.HardwareList)
{
<div class="row">
<div class="col-lg-2">
#Html.EditorFor(h => hw.Quantity, "Int32")
</div>
<div class="col-lg-2">
#Html.DisplayFor(h => hw.Partnumber)
</div>
<div class="col-lg-8">
#Html.DisplayFor(h => hw.PartName)
</div>
</div>
}
My custom editor, is textbox with some bootstrap css to make look pretty. This generates nice simple view but all of my text boxes have a nameof "hw.Quantity" and id of "hw_Quantity". So I can't use getElementById(), if I change the id the textboxes when I go to post the model, I get null list. I feel like I must be missing something super simple.
editor template
#model int?
#{
int i;
if (!Model.HasValue)
{
i = 0;
}
else
{
i = Model.Value;
}
var htmlAttributes = new RouteValueDictionary();
if (ViewBag.#class != null)
{
htmlAttributes.Add("class", "form-control " + ViewBag.#class);
}
else
{
htmlAttributes.Add("class", "form-control");
}
if (ViewBag.placeholder != null)
{
htmlAttributes.Add("placeholder", ViewBag.placeholder);
}
}
<div class="form-group#(Html.ValidationErrorFor(m => m, " has-error")) input-group">
#Html.TextBox(
"",
ViewData.TemplateInfo.FormattedModelValue,
htmlAttributes)
#Html.ValidationMessageFor(m => m, null, new { #class = "help-block" })
</div>
I'm assuming you have the remove button for every row, on click of that button you can execute a javascript function that can look into the clicked button's parent ".row" and change the "hw.Quantity" value in that row. Like
onclick="javascript:$(this).parents('.row').find('elementid').val(0);"
Additionally you can use Html's data- attributes to store additional data..
For each row add unique "data-" attribute , maybe row id. I am sure you have to have an Id per a row.
htmlAttributes('data-id', {rowid})
You will have to pass this rowId to your custom editor.
Than If you have a remove or clear button per row you can add simple javascript on it
<button class="btn btn-default" type="button" onclick="$('[data-id=#rowId]').val(0)">Remove</button>
I have a view with two drop downlist which is used to search the description. The list of results are displayed in another view for now. I wish to generate the results in the same search view. I assume some AJAX or Jquery can be used to sort this out but don't know how. So, in this case how can the search result be displayed in the same view page?
Moreover, i have some doubt in Search controller. I want at least one drop down list to be selected (Both drop down list shouldn't be allowed null). How can i validate that part?
View
#using (Html.BeginForm("Search","Work",FormMethod.Get))
{
<fieldset>
<legend>Search</legend>
<div class="editor-label">
#Html.LabelFor(model => model.JobTypeID, "Job Type")
</div>
<div class="editor-field">
#Html.DropDownList("JobTypeID", "Select Job Type")
</div>
<div class="editor-label">
#Html.LabelFor(model => model.JobPriorityID, "Job Priority")
</div>
<div class="editor-field">
#Html.DropDownList("JobPriorityID", "Select Job Priority")
</div>
<p>
<input type="submit" value="Search" />
</p>
</fieldset>
}
Controller:
[HttpGet]
public ActionResult Search(int? jobtypeid, int? jobpriorityid)
{
var vJobDescriptions = new List<JobDescription>();
if (jobtypeid != null && jobpriorityid != null )
{
vJobDescriptions = (from description in db.JobDescriptions
where (description.JobTypeID == jobtypeid && description.JobPriorityID == jobpriorityid)
select description).ToList();
}
else if (jobtypeid == null && jobpriorityid != null)
{
vJobDescriptions = (from description in db.JobDescriptions
where (description.JobPriorityID == jobpriorityid)
select description).ToList();
}
else if (jobtypeid != null && jobpriorityid == null)
{
vJobDescriptions = (from description in db.JobDescriptions
where (description.JobTypeID == jobtypeid)
select description).ToList();
}
else
{
vJobDescriptions = (from description in db.JobDescriptions
select description).ToList();
}
return View(vJobDescriptions);
}
One possibility is to use an Ajax.BeginForm instead of a normal form (don't forget to include jquery.js and jquery.unobtrusive-ajax.js scripts to your page):
#using (Ajax.BeginForm("Search", "Work", new AjaxOptions { UpdateTargetId = "results" }))
then you could have a placeholder for the results that we specified in the UpdateTargetId:
<div id="results"></div>
Now all that's left is to have your Search controller action return a PartialView and pass it the model containing the results of the search:
public ActionResult Search(int? jobtypeid, int? jobpriorityid)
{
var model = ...
return PartialView("_Result", model);
}
and of course the corresponding _Result.cshtml partial:
#model IEnumerable<MyViewModel>
...
Moreover, i have some doubt in Search controller. I want at least one
drop down list to be selected (Both drop down list shouldn't be
allowed null). How can i validate that part?
I would recommend you FluentValidation.NET but if you don't want to use third party libraries you could write a custom validation attribute that will perform this validation and then decorate one of the 2 view model properties that are bound to your dropdown lists with it.
Unfortunately if you decide to go the AJAX route, you will have to be able to display validation errors coming from the server in case there was something wrong. So it is the entire form that has to be put inside the partial.
Another approach that you could use is to simply reload the entire page using a standard form without AJAX. The results will be part of your initial view model as a collection property which will initially be null and after performing the search you will populate it with the results. Then inside the view you will test if the property is not null and if it isn't include the Partial that will take care of rendering the results:
#using (Html.BeginForm("Search", "Work", FormMethod.Get))
{
...
}
<div id="results">
#if (Model.Results != null)
{
#Html.Partial("_Results", Model.Results)
}
</div>
A basic approach to this would be to place the markup for your search results into a partial view, and return that from your Search ActionMethod. This would require you to change the last line of your search method to
return Partial(vJobDescriptions)
In your client-side script, you would do something along the lines of this:
var data = $("form").serialize();
$.get("/Search", data)
.complete(function(results) {
$("form").replace(results) };
With regards to the validation aspect you're looking for, I would consider separating your read model from the search command parameters.
public ActionResult Search(SearchModel search)
{
if (!ModelState.IsValid) // return view w/ invalid model
}
where your search params model would be along these lines:
[CustomValidation(typeof(SearchModel),
"OneNotNullValidator",
"One option must be selected"]
public class SearchModel
{
public int? JobTypeID { get; set;}
public int? JobPriorityID { get; set;}
public bool OneNotNullValidator()
{
return JobTypeID.HasValue || JobPriorityID.HasValue;
}
}
The CustomValidation attribute I've applied to the class may not be 100% correct on the specific syntax and name(s), but I hope the gist of it comes across.