I have a question on how to achieve the following:
I have a dropdownlist with activities and I want on the onchange event of an activity, that my list would be fetched with the id that is set in my model with ajax
example of my code is as following
Ajax Method to set The ID
function GetSelectedValue(DropDownID, HiddenFieldID) {
$('#' + HiddenFieldID).val($('#' + DropDownID + ' option:selected').val());
$('#' + DropDownID).change(function () {
$('#' + HiddenFieldID).val($('#' + DropDownID + ' option:selected').val());
$.ajax({
url: 'Afmeldingen',
type: "POST",
data: JSON.stringify({ 'ActiviteitenID': $('#' + DropDownID + ' option:selected').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
jQuery.globalEval(data.Callback);
},
error: function (error) {
//alert(error);
}
});
});
}
$(document).bind('pageinit', function () {
GetSelectedValue('details', 'act_id');
});
The Form element
#using (Html.BeginForm())
{
<div data-role="collapsible" data-inline="true" data-content-theme="b" data-collapsed="false">
<h3>#DateTime.Today.ToShortDateString()</h3>
<div data-role="collapsible-set" data-inline="true" data-content-theme="b" data-collapsed="true">
<select id="details">
#foreach (var item in Models.Taken.ActivityList)
{
<option value="#item.ID">#item.Comments</option>
}
</select>
#Html.Hidden("act_id")
#foreach (var item in Talent.Subscription.Fetch(null, Models.Taken.ActID ?? 1L, null, null))
{
<div data-role="collapsible" data-content-theme="b" data-collapsed="true">
<h3>
#Html.Label("", item.Participant.CompleteName)
</h3>
#Html.CheckBoxFor(m => m.DeelnemerActive.HasValue, htmlAttributes: new { data_role = "CheckBox" })
#foreach (var af in Talent.Afmelding.Fetch(null, Models.Tasks.ActID ?? 1L, null, null))
{
#Html.Label("", "Comments")
#Html.TextBox("Reason", af.Reason);
}
</div>
}
</div>
</div>
}
I hope you can help me to achieve this, or that you have an idea how to do this
This is probably the best example I can find that would help you.
http://blog.krisvandermast.com/CommentView,guid,b1a264ac-c48f-463e-9f55-db24e2a9b635.aspx
He loads data from a partial view dynamically on the onclick of a
button. You could use your onchange here.
-
Have a look at this example to see how cascading dropdowns work:
http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/cascading-dropdownlist-in-Asp-Net-mvc/
-
You could also consider using knockout js, like described here:
http://www.dotnetexpertguide.com/2012/06/cascading-dropdown-knockoutjs-aspnet.html
Related
I want to click "2" Ajax will call ActionResult and put new question up but not rerun page
i have been trying two day but it haven't worked
People help me, please
ActionResult:
[HttpPost]
public ActionResult BaiTestIQ(int id)
{
var cauhoi = from q in data.Questions
join a in data.Answers on q.MaTests equals "IQ"
where q.MaCHoi == a.MaCHoi && a.keys == id
select new baitest()
{
Cauhoi = q.Noidung,
DAn1 = a.DAn1,
DAn2 = a.DAn2,
DAn3 = a.DAn3,
DAn4 = a.DAn4,
DAn5 = a.DAn5,
DAn6 = a.DAn6,
};
return View(cauhoi);
}
Function Ajax:
<script>
function loadcauhoi(num) {
$.ajax({
dataType: "Json",
type: "POST",
url: '#Url.Action("BaiTestIQ","TestIQ")',
data: { id: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)}
});
}
</script>
In HTML:
<li>
1
</li>
enter image description here
Thanks for reading
I changed but it dont work!!
I learned it myself so it was hard to get started
ActionResult:
[HttpPost]
public ActionResult BaiTestIQ(int id)
{
var cauhoi = from q in data.Questions
join a in data.Answers on q.MaTests equals "IQ"
where q.MaCHoi == a.MaCHoi && a.keys == id
select new baitest()
{
Cauhoi = q.Noidung,
DAn1 = a.DAn1,
DAn2 = a.DAn2,
DAn3 = a.DAn3,
DAn4 = a.DAn4,
DAn5 = a.DAn5,
DAn6 = a.DAn6,
};
return PartialView(cauhoi);
}
Function Ajax:
<script>
function loadcauhoi(num) {
$.ajax({
dataType: "Html",
type: "POST",
url: '#Url.Action("BaiTestIQ","TestIQ")',
data: { id: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#baitetstiq').html(a);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)}
});
}
</script>
Full HTML:
<div class="col-md-9" style="border-top-style:double;
border-top-color:aquamarine;
border-top-width:5px; margin-left:-15px">
<p style="text-align:center">
<b>Thời Gian Còn Lại Là:xxx</b>
</p>
<div id="baitestiq"></div>
#foreach(var item in Model)
{
<div class="baitest">
<div class="ques">
<img src="~/Hinh_Cauhoi/#item.Cauhoi" />
</div>
<div class="anw">
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn1" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn2" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn3" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn4" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn5" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn6" />
</div>
</div>
<div class="numbertest">
<ul>
<li>
1
</li>
</ul>
</div>
1st you need to return a partial view.
2nd you need to make a get ajax request and not a post
3rd you need to test first the result of #Url.Action("BaiTestIQ","TestIQ"), translate this to a URL, directly to make sure it returns the expected results without the ajax call to avoid getting into sideways with routing etc. see this for example
See a working example here
Update:
I see it now, you changed dataType: "Html"
You need to change several things:
1. The method is not changing any state so it should not be declared as a post method. You need to remove [HttpPost] attribute.
You need to be aware of ajax parameters contentType and dataType. From the documentation: contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8'). This specifies what type of data you're sending to the server. And dataType (default: Intelligent Guess (XML, json, script, or HTML)) specifies what jQuery should expect to be returned. In your case, it should be 'json' because you are using the result return from a LINQ query.
So the method might look like:
public JsonResult BaiTestIQ(int id)
{
var cauhoi = from q in data.Questions
join a in data.Answers on q.MaTests equals "IQ"
where q.MaCHoi == a.MaCHoi && a.keys == id
select new baitest()
{
Cauhoi = q.Noidung,
DAn1 = a.DAn1,
DAn2 = a.DAn2,
DAn3 = a.DAn3,
DAn4 = a.DAn4,
DAn5 = a.DAn5,
DAn6 = a.DAn6,
};
return Json(cauhoi.ToList(), JsonRequestBehavior.AllowGet);
}
3. Moving to the ajax call:
<script>
function loadcauhoi(num) {
$.ajax({
url: '#Url.Action("BaiTestIQ","TestIQ")',
data: { id: num },
type: "GET",
cache: false,
dataType: "json",
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)}
});
}
</script>
**But I'd like to suggest another approach using a ViewModel with a partial view because serializing JSON data can sometimes get you errors. A quick tutorial
I want to pass selected value of dropdownlist from view to controller in html.BeginForm in MVC 4.
I can pass value of query string, but I have no idea about how to pass selected value of dropdownlist.
All suggestions are most welcome.
Here is my code attached
<form>
<fieldset class="form-group" id="ddl2">
<label for="exampleSelect1">Section Type:</label>
#(Html.Kendo().DropDownList()
.Name("ddlsection")
.DataTextField("Name")
.DataValueField("Id")
.OptionLabel("--Select--")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetSectionType", "LookUp");
});
})
.Events(e => e.Change("onChange_ddlsection"))
.HtmlAttributes(new { #class = "form-control" })
)
</fieldset>
</form>
<div class="WordClass">
#using (Html.BeginForm("GetConditionListingInWord", "Inspection", new { sectionId = 'What should be here?' }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="Submit1" type="submit" value="" class="WordClassA tooltipSource" title='Print List in MS-Word format' data-placement='bottom' data-toggle='tooltip' />
}
</div>
I want 'ddlsection' dropdown's selected value in 'What should be here?' section.
You can pass Kendo Dropdownlist's selected value to the Controller using Ajax call and then redirect to another Action if you want as shown below:
<script type="text/javascript">
$(function () {
//Returns Dropdownlist's selected values to the Controller
$("#btnSubmit").click(function (e) {
e.preventDefault();
var data = {
ProjectID: $('#ProjectID').val(), //parameter I
IssueID: $('#IssueID').val() //parameter II
}
$.ajax({
type: "POST",
url: "/Controller/Action",
cache: false,
data: JSON.stringify(data),
dataType: this.dataType,
contentType: "application/json; charset=utf-8",
success: function (data) {
// Variable data contains the data you get from the action method
window.location = "/Controller/OtherAction/" + data
},
error: function (data) {
$("#error_message").html(data);
}
});
});
});
</script>
For that you have to make AJAX call to your controler method
var userModel = {
RoleId: $("#drpRoleId").data("kendoDropDownList").value(),
}
$.ajax({
url: '#Url.Action("AddEditUser","User")',
type: 'POST',
data: JSON.stringify(userModel),
async: true,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
}
});
I am new in ajax and I need a help.
This is a script that populates second dropdownlist once first is selected.
It works fine using GetStates action that gets data from database.
<script type="text/javascript">
$(document).ready(function () {
$("#CountriyID").change(function () {
var abbr = $("#CountriyID").val();
$.ajax({
url: "/SetUp/GetStates",
data: { countryCode: abbr },
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred.");
},
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
$("#StateID").html(items);
}
});
});
});
</script>
Here is the view that I am working on
#using (Html.BeginForm("Index", "SetUp", FormMethod.Post))
{
<form action="" method="post">
<input type="submit" name="action:AddCity" value="Add" />
</form>
<div class="editor-field">#Html.DropDownListFor(model => model.CountriyID, new SelectList(Model.Countries, "ID", "Text"))</div>
<div class="editor-field">#Html.DropDownListFor(model => model.StateID, new SelectList(Model.States, "ID", "Text"))</div>
}
If I need to add a City I click on a submit button and it goes to correct action.
The problem happened when I populate dropdownlist. After population, the City button do not respond anymore. It looks like the url get stack at "/SetUp/GetStates" and I cannot do any actions anymore on my form.
Please Let me know what am I doing wrong and where to take a look?
Thanks in advance.
try the below code hope it helps you:
<form action="" method="post">
<div class="editor-field">#Html.DropDownListFor(model => model.CountriyID, new SelectList(Model.Countries, "ID", "Text"))</div>
<div class="editor-field">#Html.DropDownListFor(model => model.StateID, new SelectList(Model.States, "ID", "Text"))</div>
<input type="submit" name="action:AddCity" value="Add" />
</form>
As the drop down must come into the tags and submit must be at the last place in the tags ideally.
I have an MVC View page, strongly-typed to an enumerated product list. Each list item has an Html.ActionLink with a unique id. In my jquery file, I have an $.ajax function which should process the link with the corresponding id . The intent is to load a partial view on the same page, with that item's information, to allow editing for whatever item has been clicked. I don't want the actionr to result in a separate page, or generate a post to the server.
// here is the MVC stuff
#model IEnumerable<SimpleAjax.Models.Product>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.ActionLink("Edit", "ShowEdit", "Home", new { id=item.Id } ,new { id = "btnShowEdit" + item.Id, #class= ".button_action"})
|
</td>
</tr>
}
<div id="showEditProd">
</div>
//inside controller
public ActionResult ShowEdit(int id)
{
Product prod = db.Product.Find(id);
ProductViewModel viewModel = new ProductViewModel
{
EditProduct = prod
};
return PartialView(viewModel);
}
//inside a separate partial view page
#model SimpleAjax.Models.ProductViewModel
#using (Html.BeginForm("Index_AddItem", "Home", FormMethod.Post, new { id = "fid" }))
{
<div>
#Html.LabelFor(model => model.EditProduct.Name)
#Html.EditorFor(model => model.EditProduct.Name)
</div>
<div>
#Html.LabelFor(model => model.EditProduct.Price)
#Html.EditorFor(model => model.EditProduct.Price)
</div>
<div>
<input type="submit" value="Submit" />
</div>
}
now below works as expected, when I have hardcoded IDs:
$('#btnShowEdit1,#btnShowEdit2,#btnShowEdit3').click(function () {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
The above jquery works as desired. The partial view gets loaded on the same page as enumerated list. But obviously I don't want to hardcode variables. I may have x number of #btnShowEdit. I want to utilize a class, correct? So I have ".button_action" class that will enumerate the Id. But when I do that, as below, the link navigates to a separate page.
these go to a separate page, not what I want
$('.button_action').click(function (index) {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
});
//also tried this...
$('.button_action').each(function (index) {
$('#btnShowEdit' + index).click(function () {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
});
I know there's gotta be a simple solution.Thanks for your help in advance.
Any specific reason for not using the Ajax HTML-helper?
http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxextensions.actionlink(v=vs.108).aspx
You can use it as an actionlink, but it is done async and the result can be placed in your showEditProd.
#Ajax.ActionLink("Action",
"Controller",
_YOURID_,
new AjaxOptions { HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "showEditProd",
OnComplete = "your_js_function();" })
In case anyone else needs the solution to the above... It was too simple to believe.The jquery ajax code does not need an id htmlattribute from the Html.ActionLink. In fact, this extra attribute is what was causing the trouble. The jquery ajax recognizes the id from the "this.href' as that is the route controller along with the id parameter. Therefore I removed the id from htmlattributes in the actionlink. Now it's working as expected.
#Html.ActionLink("Edit", "ShowEdit", "Home", new { id=item.Id } ,new { #class= ".button_action"})
in js file
$('.button_action').click(function (index) {
$.ajax({
url: this.href,
contentType: 'application/html; charset=utf-8',
type: 'GET',
success: function (result) {
$('#showEditProd').html(result);
}
});
return false;
});
});
Check this:
$('.button_action').click(function (e) {
e.preventDefault() // this prevent default behavior for hyperlink on 'click' event
I have a little problem when trying to get the value of a local int variable on a view, using jQuery. So, I have a the main view, and as you can see in the code below, I use a partial view named "_Result", when I try to get the value of indexPage by handling the click event of a button in the partial view, I get 0, event if I initialize my variable by another value(5 for example). Any idea why ?
Thanks in advance
My view :
#model System.Data.DataTable
#{var pageIndex = 5;}
<div>
<div>
<span>Téléphone ?</span>
<input id="idTxTel" type="text" name="txTelephone"/>
<input id="idBnSearch" type="submit" value="Chercher" name="bnSearch"/>
</div>
#Html.Partial("_Result", Model)
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#idBnSearch").click(function () {
//The right value (5)
alert('#pageIndex');
var telValue = $("#idTxTel").val();
var methodUrl = '#Url.Content("~/Search/GetReverseResult/")';
'#{pageIndex = 0;}'
doReverseSearch(telValue, '#pageIndex', methodUrl);
});
$("#bnNextPage").live("click", function ()
{
//Not th right value (0)
alert('#pageIndex');
});
});
</script>
My doReverseSearch method :
function doReverseSearch(telValue, pageIdx, methodUrl)
{
$.ajax(
{
url: methodUrl,
type: 'post',
data: JSON.stringify({ Telephone: telValue, pageIndex: pageIdx }),
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#result').replaceWith(data);
},
error: function (request, status, err) {
alert(status);
alert(err);
}
});
}
My partial view :
<div id="result">
<h2>Résultat de la recherche</h2>
<div>#ViewBag.CountResult entreprises trouvées</div>
#if(Model != null)
{
foreach (DataRow row in Model.Rows)
{
<h3>#row["CompanyName"]</h3>
}
}
<hr />
<div>
<span>Page N sur M</span>
<input id="bnPreviousPage" type="submit" value="Précédant" name="bnPrevious"/>
<input id="bnNextPage" type="submit" value="Suivant" name="bnNext"/>
</div>
</div>
Razor inside javascript has to be wrapped in a block
so you can do this:
<script>
// global value for page
<text>
var myPage = #pageIndex;
<text>
</script>
what would be far easier is give the button an attribute of data-page and ask for attribute in click event:
<button data-page="#("pageIndex")" id="myButt" />
$("#myButt").on("click",function(e){
var pageIndex = $(this).attr("data-page");
alert(pageIndex);
});