how can i load second dropdown on selection of first and third on second. in asp.net mvc 2
I have the dropdown trigger an ajax post that sends the selected ID selected to a controller and then return a partial view which overwrites the html for a placeholder div.
View; this sets the ActionUrl, you will also need a placeholder div (in my case called departments) for the drop down to be injected:
<script type="text/javascript">
var ActionUrl = '<%= Url.Action("RenderDepartments", "ControllerName") %>';
</script>
<script src="<%: ResolveUrl("~/Scripts/Custom/DepartmentFilter.js")%>" type="text/javascript"></script>
<%: Html.DropDownListFor(model => model.OfficeId, Model.ListItems, "-- Please Select --", new { onchange = "GetDepartments()" })%>
// ^^ ON CHANGE IS IMPORTANT ^^
<div id="departments"></div>
JQuery;
function GetDepartments() {
$.ajax(
{
type: "POST",
url: ActionUrl,
data: { officeId: $("#OfficeId").val() },
success: function (data) {
$("#departments").html(data);
}, error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('XMLHttpRequest:' + XMLHttpRequest.responseText);
alert('textStatus:' + textStatus);
//alert('errorThrown:' + errorThrown);
}
});
}
Controller Action;
public ActionResult RenderDepartments(int? officeId)
{
if (officeId.HasValue)
{
var departments = new SelectList(ents.GetDepartments(officeId), "departmentID", "Name");
var model = new DropdownListViewModel(departments);
return PartialView("DepartmentDropdown", model);
}
return null;
}
This is nullable because the user could submit "-- please select --" which will in this case return null and remove the departments dropdown.
Related
I've found a video from SharePointTech that explains how to change a textfield to a dropdown list on a List Form using data from open API. I'm trying to recreate it, but I'm hitting a roadblock with the new SharePoint Online. Instead of using "Country/Region", I created a new custom list with Company_Name. I took the person's code and made little changes that made a reference to "WorkCountry". When I save the changes (stop editing), the changes do not reflect and I get the same textfield. I had to use SharePoint Designer 2013 to create a new TestNewForm for new entry. Has anyone been able to reproduce this in SharePoint 2013 Designer? If so, would you be able an example?
I use jQuery's ajax method.
Updated code for your reference(you need to change the list name to your list name,InternalName is also):
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
var demo = window.demo || {};
demo.nodeTypes = {
commentNode: 8
};
demo.fetchCountries = function ($j) {
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('Company_Name')/items",
type: "get",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
$j('table.ms-formtable td.ms-formbody').contents().filter(function () {
return (this.nodeType == demo.nodeTypes.commentNode);
}).each(function (idx, node) {
if (node.nodeValue.match(/FieldInternalName="Country_x002f_Region"/)) {
// Find existing text field (<input> tag)
var inputTag = $(this).parent().find('input');
// Create <select> tag out of retrieved countries
var optionMarkup = '<option value="">Choose one...</option>';
$j.each(data.d.results, function (idx, company) {
optionMarkup += '<option>' + company.Title + '</option>';
});
var selectTag = $j('<select>' + optionMarkup + '</select>');
// Initialize value of <select> tag from value of <input>
selectTag.val(inputTag.val());
// Wire up event handlers to keep <select> and <input> tags in sync
inputTag.on('change', function () {
selectTag.val(inputTag.val());
});
selectTag.on('change', function () {
inputTag.val(selectTag.val());
});
// Add <select> tag to form and hide <input> tag
inputTag.hide();
inputTag.after(selectTag);
}
});
},
error: function (data) {
console.log(data)
}
});
}
if (window.jQuery) {
jQuery(document).ready(function () {
(function ($j) {
demo.fetchCountries($j);
})(jQuery);
});
}
</script>
My source list:
Test result:
Updated:
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
var demo = window.demo || {};
demo.nodeTypes = {
commentNode: 8
};
demo.fetchCountries = function ($j) {
$.ajax({
url: 'https://restcountries.eu/rest/v1/all',
type: "get",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
$j('table.ms-formtable td.ms-formbody').contents().filter(function () {
return (this.nodeType == demo.nodeTypes.commentNode);
}).each(function (idx, node) {
if (node.nodeValue.match(/FieldInternalName="Country_x002f_Region"/)) {
// Find existing text field (<input> tag)
var inputTag = $(this).parent().find('input');
// Create <select> tag out of retrieved countries
var optionMarkup = '<option value="">Choose one...</option>';
$j.each(data, function (idx, company) {
optionMarkup += '<option>' + company.name + '</option>';
});
var selectTag = $j('<select>' + optionMarkup + '</select>');
// Initialize value of <select> tag from value of <input>
selectTag.val(inputTag.val());
// Wire up event handlers to keep <select> and <input> tags in sync
inputTag.on('change', function () {
selectTag.val(inputTag.val());
});
selectTag.on('change', function () {
inputTag.val(selectTag.val());
});
// Add <select> tag to form and hide <input> tag
inputTag.hide();
inputTag.after(selectTag);
}
});
},
error: function (data) {
console.log(data)
}
});
}
if (window.jQuery) {
jQuery(document).ready(function () {
(function ($j) {
demo.fetchCountries($j);
})(jQuery);
});
}
</script>
The difference in API will not have a great effect, the key is here '$ j.each (data, function (idx, company) {'. The structure of the return value of different APIs are different, you need to find useful data in return value.
I have 2 questions:
1.) I have placed the Fine Uploader in a form and now I'm wondering why I don't see the filled content of the entry fields in my controller. How I can solve that?
2.) How can I do field validations before the upload process fires?
I hope someone can help!
Here is my code:
Model:
public class UploadFileModel
{
[StringLength(100)]
[Display(Name = "* Title:")]
public string Title { get; set; }
[StringLength(300)]
[Display(Name = "Description:")]
public string Description { get; set; }
}
View:
#model mowee.Models.UploadFileModel
<link href="~/Scripts/fineuploader/fineuploader-3.5.0.css" rel="stylesheet" />
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { id = "uploadForm", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<fieldset>
<legend>Video Upload</legend>
<ol>
<li>
#Html.LabelFor(m => m.Title)
#Html.TextBoxFor(m => m.Title, new { #Class = "action add", title = "Enter your video/movie title here." })
</li>
<li>
#Html.LabelFor(m => m.Description)
#Html.TextAreaFor(m => m.Description, new Dictionary<string, object> { { "rows", "3" } })
</li>
</ol>
<div id="bootstrapped-fine-uploader"></div>
<script src="~/Scripts/fineuploader/fineuploader-3.5.0.js"></script>
<script>
function createUploader() {
var uploader = new qq.FineUploader({
element: document.getElementById('bootstrapped-fine-uploader'),
multiple: false,
validation: {
sizeLimit: 2147483648 //2GB
},
request: {
endpoint: '/Home/UploadFile'
},
text: {
uploadButton: '<div><i class="icon-upload icon-white"></i>* Upload Video</div>'
},
template: '<div class="qq-uploader span12">' +
'<pre class="qq-upload-drop-area span12"><span>{dragZoneText}</span></pre>' +
'<div id="btnUpload" class="qq-upload-button btn btn-success" style="width: 33%;">{uploadButtonText}</div>' +
'<span class="qq-drop-processing"><span>{dropProcessingText}</span><span class="qq-drop-processing-spinner"></span></span>' +
'<ul class="qq-upload-list" style="margin-top: 10px; text-align: center;"></ul>' +
'</div>',
classes: {
success: 'alert alert-success',
fail: 'alert alert-error',
dropActive: "cssClassToAddToDropZoneOnEnter"
}
});
}
window.onload = createUploader;
</script>
</fieldset>
}
Controller:
[HttpPost]
[AllowAnonymous]
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult UploadFile(string qqfile, UploadFileModel myModel)
{
if (ModelState.IsValid)
{
try
{
HttpPostedFileBase uploadFile = null;
uploadFile = Request.Files[0];
if (uploadFile != null && uploadFile.ContentLength > 0)
{
if (myModel.Title != null || myModel.Description != null)
{
**//but UploadFileModel is null. WHY??????? Anyone an idea what i did wrong???
//write data to DB**
}
}
else
{
ModelState.AddModelError("", "Please choose a video/movie.");
return Json(new { success = false, message = "Please choose a video/movie." }, "application/json");
}
}
catch (Exception ex)
{
ModelState.AddModelError("", "An error occured. Try again.");
mailUtils.SendBugMail(ex, this.HttpContext);
return Json(new { success = false, message = "An error occured during upload. Try again." }, "application/json");
}
return Json(new { success = true, VideoLink = #ViewBag.VideoLink, VideoTranscoded = #ViewBag.Transcoded }, "application/json");//"text/html");
}
return Json(new { success = false, message = "An error occured during upload. Try again." }, "application/json");
}
OK. I figured it out. The params can be set on callback 'onSubmit' with setParams like that:
callbacks: {
onSubmit: function (id, fileName, responseJSON) {
uploader.setParams({
idxTitle: $('#titleId').val(),
idxAuthor: $('#authorId').val(),
idxEmail: $('#emailId').val()
});
},
And it works fine!
Addressing your questions:
You should really have a look at the MVC4 example in the Fine Uploader server-side examples repository. Model your server-side code after this example, and you should be fine. I personally am not an MVC4 developer, but I know the example I have linked to works.
You can make use of onValidate and onValidateBatch callbacks to perform your own validation tasks. Please have a look at the callbacks documentation for more info.
I am trying to pass the object myclass to the view page, the issue I am facing is null object is being returned back to the controller. Any pointers ?
Below is the code in my ascx page
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<myclass>" %>
<div class="upModel" style="display:none">
<%= Model%>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#load").click(function () {
try {
$.ajax({
type: "POST",
url: "Loadmyaction",
data: $("#upModel").serialize(),
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
},
error: function(result) { alert("Error" + result); }
});
}
catch (err) {
alert(err.description);
}
});
</script>
**On controller, this is my method**
public string Loadmyaction(string obj)
{
string str = "";
return str;
}
Here obj is getting null from the view. Why is that no data is being passed back to the controller ?
Are you sure it's actually hitting your method?
Your jquery should look like this:
$.ajax({
type: "POST",
url: "<%=Url.Action("Loadmyaction") %>",
data: $("#upModel").serialize(),
dataType: "json",
success: function(data) {
alert(data);
},
error: function(result) {
alert("Error" + result);
}
});
Try changing your parameter type to myClass, whatever it might be.
[HttpPost]
public JsonResult LoadMyAction(MyClass model)
{
return Json("someString");
}
<%: Html.ActionLink("Cancel", "Edit", "Users", new {id = " + userID + " }, null) %>
In the code above userId is a variable. This syntax is not right, what should it be?
You cannot use an HTML helper which is run on the server to use a Javascript variable which is known on the client. So you need to generate your URL with the information you dispose on the server. So all you can do on the server is this:
<%: Html.ActionLink("Cancel", "Edit", "Users", null, new { id = "mylink" }) %>
Then I suppose that on the client you are doing some javascript (ideally with jquery) and a moment comes when you want to query the server using this url and the userID you've calculated on the client. So for example you could modify the link action dynamically by appending some id:
$(function() {
$('#mylink').click(function() {
var userId = ...
this.href = this.href + '?' + userId;
});
});
or if you wanted to AJAXify this link:
$(function() {
$('#mylink').click(function() {
var userId = ...
$.ajax({
url: this.href,
data: { id: userId },
success: function(result) {
...
}
});
return false;
});
});
How can i make an image as an Ajax Action Link?
You could do this:
<a href="<%: Url.Action("someaction", "somecontroller") %>" id="mylink">
<img src="<%: Url.Content("~/images/foo.png") %>" alt="foo" />
</a>
and then in a separate javascript file AJAXify this link:
$(function() {
$('#mylink').click(function() {
$.ajax({
url: this.href,
type: 'GET',
success: function(result) {
alert('success');
}
});
return false;
});
});
And if you want to avoid the tag soup in your views you could write a custom helper:
public static class HtmlExtensions
{
public static MvcHtmlString ImageLink(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues, object htmlAttributes, string imageSource)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
var image = new TagBuilder("img");
image.Attributes["src"] = urlHelper.Content(imageSource);
var anchor = new TagBuilder("a");
anchor.Attributes["href"] = urlHelper.Action(actionName, controllerName, routeValues);
anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
anchor.InnerHtml = image.ToString(TagRenderMode.SelfClosing);
return MvcHtmlString.Create(anchor.ToString());
}
}
and then in your view simply:
<%: Html.ImageLink(
"someaction",
"somecontroller",
null,
new { id = "mylink" },
"~/images/foo.png"
) %>
and of course the process of AJAXifying it stays the same.
What about something like:
<a href='<%= Url.Action(...) %>'><img src='...' /></a>
Not certain if there is a helper that does this.
Bob
To push the id to the edit control whilst displaying an edit image instead of the word Spag you can try this:
#MvcHtmlString.Create(
Ajax.ActionLink("Spag", "Edit",
new { id = item.x0101EmployeeID },
new AjaxOptions() {
UpdateTargetId = "selectDiv",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
}
).ToHtmlString().Replace(
"Spag",
"<img src=\"" + Url.Content("../../Images/edit.png") + "\" />"
)
)