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") + "\" />"
)
)
Related
How can I send a single string value through view from in the WebAPI made in ASP.NET core.
Here is my API:
[HttpPost]
[Route("studentlogin/{value}")]
public IActionResult StudentLogin(string value)
{
string name = String.Concat(value.Where(s => !Char.IsWhiteSpace(s)));
name = name.ToLower();
var newStudent = new Student();
newStudent.FullName = name;
db.Entry(newStudent).State = EntityState.Added;
db.SaveChanges();
var selectStudent = db.Students.Where(ss => ss.FullName == name).FirstOrDefault();
var id = selectStudent.Id;
string idToString = id.ToString();
string answer = sha384converter(idToString);
selectStudent.HashId = answer;
db.Entry(selectStudent).State = EntityState.Modified;
db.SaveChanges();
return Ok();
}
I want to send paramenter value in it through View Forms, How can I send data in it?
Thanks in advance.
[Route("studentlogin/{value}")]
If you are using the above route, the request URL should like this: https://localhost:44310/api/apicontrollername/studentlogin/XXX, the parameter will be transferred from the URL and route.
to send paramenter value in it through View Forms, How can I send data
in it?
To send parameter value from posted form fields, you could modify the code as below:
In the API controller, remote the route parameter and add the FromForm attribute.
[HttpPost]
[Route("studentlogin")]
public IActionResult StudentLogin([FromForm]string value)
{
string name = "Default value";
if (!string.IsNullOrEmpty(value))
{
name = String.Concat(value.Where(s => !Char.IsWhiteSpace(s)));
}
... // add your code
return Ok(name);
}
Then, create a model which contain the value property, like this:
public class StudentLoginViewModel
{
public string value { get; set; }
}
In the View page, display the above model in the form:
#model WebApplication6.Models.StudentLoginViewModel;
<form id="myform">
<div class="form-group">
<label asp-for="value" class="control-label"></label>
<input asp-for="value" class="form-control" />
<span asp-validation-for="value" class="text-danger"></span>
</div>
<div class="form-group">
<input type="button" id="btnsubmit" value="Submit" class="btn btn-primary" />
</div>
</form>
and add the following script at the end of the above view page:
#section Scripts{
<script>
$(function () {
$("#btnsubmit").click(function () {
//use the serialize() method to encode a set of form elements as a string for submission
var data = $("#myform").serialize();
//you can also create JavaScript object and send the data.
//var data = { value: $("#value").val() };
$.ajax({
url: '/api/todo/studentlogin', // change the url to yours.
type: "post",
contentType: 'application/x-www-form-urlencoded',
data: data,
success: function (result) {
console.log(result);
}
});
});
})
</script>
}
The result as below:
The Excel sheet want to read while it upload on a button click in MVC5.The uploaded excel file name is passed into action using AJAX method.Here the file variable get null value in posted method.
Here how can pass selected file as HttpPostedFileBase in the below ajax method.
`
<input style="display:none" type="file" id="fileupload1" />
<button type="button" onclick='$("#fileupload1").click()'>UPLOAD FROM EXCEL</button>
<span style="display:none" id="spnName"></span>
$(function () {$("#fileupload1").change(function () {
$("#spnName").html($("#fileupload1").val().substring($("#fileupload1").val().lastIndexOf('\\') + 1));
var file = $("#spnName").html();
$.ajax({
url: "UploadExcelForContractStaff",
type: 'POST',
data: JSON.stringify({ file: file }),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
}
});
});
});`
[AcceptVerbs(HttpVerbs.Post)]
public string UploadExcelForContractStaff(HttpPostedFileBase uploadFile)
{
StringBuilder strValidations = new StringBuilder(string.Empty);
try
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
DataSet ds = new DataSet();
//A 32-bit provider which enables the use of
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";
using (OleDbConnection conn = new System.Data.OleDb.OleDbConnection(ConnectionString))
{
conn.Open();
using (DataTable dtExcelSchema = conn.GetSchema("Tables"))
{
string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
string query = "SELECT * FROM [" + sheetName + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
//DataSet ds = new DataSet();
adapter.Fill(ds, "Items");
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
//Now we can insert this data to database...
}
}
}
}
}
}
}
catch (Exception ex) { }
return "";
}
I got solution. changed code like
<form enctype="multipart/form-data" id="frmUplaodFileAdd">
#Html.AntiForgeryToken()
<input style="display:none" type="file" id="fileupload1" />
<button type="button" onclick='$("#fileupload1").click()'>UPLOAD FROM EXCEL</button>
<span style="display:none" id="spnName"></span>
</form>
$.ajax({
url: "UploadFile", //Server script to process data
type: 'POST',
async: false,
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress',
progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function (data) { }
});
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{return Json();
}
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.
<%: 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 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.