Delete files in Edit view - c#

In my application I try to delete single files from Edit view. It works ok, but doesn't refresh a site.
Item in FileDetails Class contains Id, Extension, FileName and TicketId(which is connected with Ticket class)
My code:
Method in Controller
#section Scripts {
<script>
$('.deleteItem').click(function (e) {
e.preventDefault();
var $ctrl = $(this);
if (confirm('Do you really want to delete this file?')) {
$.ajax({
url: '#Url.Action("DeleteFile")',
type: 'POST',
data: { id: $(this).data('id') }
}).done(function (data) {
if (data.Result == "OK") {
$ctrl.closest('li').remove();
}
else if (data.Result.Message) {
alert(data.Result.Message);
}
}).fail(function () {
alert("There is something wrong. Please try again.");
})
}
});
</script>
}
<div class="form-group">
<div class="col-md-10">
<p>Upload one or more files</p>
<input type="file" name="file" multiple />
</div>
<ul class="attachment">
#foreach (var item in Model.Ticket.FileDetails)
{
<li>
<a class="title" href="/Tickets/Download/?fileName=#(item.Id + item.Extension)&ticketId=#item.TicketId">#item.FileName</a>
X
</li>
}
</ul>
I get TypeError: data.Result is undefined

Check your data variable before getting its Result property. Your data should be available in data.

Related

FormData not binding values to controller

I have an Asp.net core application in which I have a form. When I click on the submit button I am using jquery ajax post to submit the form. I am facing 2 problems here,
When I press the submit button, the client side validations are not happening and the form is being submitted.
I have a Break point in the SendEmail Method, and for some reason the FormData binds all null values to the object. Please help.
Here is my form
<form name="ajax-form" id="formPostComment" enctype="multipart/form-data" method="post">
<div class="col-sm-6 contact-form-item wow zoomIn">
<input name="name" id="name" type="text" placeholder="Your Name: *" required/>
<span class="error" id="err-name">please enter name</span>
</div>
<div class="col-sm-6 contact-form-item wow zoomIn">
<input name="email" id="email" type="text" placeholder="E-Mail: *" required/>
<span class="error" id="err-email">please enter e-mail</span>
<span class="error" id="err-emailvld">e-mail is not a valid format</span>
</div>
<div class="col-sm-6 contact-form-item wow zoomIn">
<label for="myfiles">Select file (If Any):</label>
<input name="attachment" id="attachment" type="file" />
</div>
<div class="col-sm-12 contact-form-item wow zoomIn">
<textarea name="message" id="message" placeholder="Your Message" required></textarea>
</div>
<div class="col-sm-12 contact-form-item">
<input class="send_message btn btn-main btn-theme wow fadeInUp" type="submit" id="submit" name="submit" data-lang="en" onclick="SendEmail();"></input>
</div>
<div class="clear"></div>
<div class="error text-align-center" id="err-form">There was a problem validating the form please check!</div>
<div class="error text-align-center" id="err-timedout">The connection to the server timed out!</div>
<div class="error" id="err-state"></div>
</form>
<script>
function SendEmail() {
var formData = new FormData();
formData.append("Name", $("#name").val());
formData.append("Email", $("#email").val());
formData.append("Attachment", $("#attachment")[0]);
formData.append("Message", $("#message").val());
alert($("#name").val());
$.ajax({
type: 'POST',
url: "/Home/SendEmail",
data: formData,
processData: false,
contentType: false,
cache: false,
success: function (response) {
alert("Done");
$('#formPostComment')[0].reset();
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
//}).done(function (data) {
// console.log(data);
// $("#ajaxwaiting").hide();
// $("#ajaxsuccess").show();
//});
event.preventDefault();
}
</script>
Here is my Controller action method.
[HttpPost]
public IActionResult SendEmail([Bind("Name,Email,Attachment,Message")] SingleEmailMessage message)
{
return Json(new { data = "DONE" });
}
The SingleEmailMessage class is as follows,
public class SingleEmailMessage
{
public string Name { get; set; }
public string Email { get; set; }
public IFormFile Attachment { get; set; }
public string Message { get; set; }
}
you might be sending two POSTs here... don't use onclick on the submit... instead use onsubmit on the form tag... ex:
<form ... onsubmit="SendEmail(); return false;"> Don't forget the "return false;" bit that replaces your event.preventDefault() call. It's also easier to pass the form's ID into your function... so
SendEmail("formPostComment")... then function SendEmail(id) {
...
thisForm = document.getElementById(id);
var formData = new FormData(thisForm);
On controller side get the file by using:
if (Request.Form.Files.Count > 0)
{
IFormFile file = Request.Form.Files[0];
}
Not sure that the file is going to bind to your model.... get it from the raw request.
The full JS function I use is this (just for reference):
//for uploads
function PostFileFormID(id, buttonid, destURL) {
$('#' + buttonid).attr('value', "Uploading...");
thisForm = document.getElementById(id);
var formData = new FormData(thisForm);
jQuery.ajax({
type: 'POST',
url: destURL,
data: formData,
processData: false,
contentType: false,
success: function (data) {
params = convertJsonToParams(data);
url = "?" + params;
setLocation(url);
},
error: function (jqXHR, textStatus, error) {
DisplaySuperError(jqXHR, textStatus, error);
}
});
}

How can I get my Popup to close on submit button from AJAX call in ASP.NET MVC?

I have a view that lists a bunch of items. I'm trying to make it so that when a user clicks on the "Action Event" for one of these items (from a table row), a pop-up will appear. The user can then update same information about this item, and either submit the information or close it. Regardless of which option they choose, I'm trying to get the pop-up window to close.
I'm 90% there, I just can't seem to work out one little detail - closing the popup after the submit button is pressed! A lot of the solutions I have seen don't appear to be working, and I just seem to be having some trouble tweaking them to work with my issue. Given the following code, what changes do I need to do to make this work?
Here is what I have:
View
Index.cshtml
<table>
#foreach (var item in Model)
<tr>
<td colspan="5" align="right">
Action Event
</td>
</tr>
}
</table>
<div id="myModal" class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div id="myModalContent"></div>
</div>
</div>
</div>
<script>
var TeamDetailPostBackURL = '/Database/Edit';
$(function () {
$(".anchorDetail").click(function () {
var $buttonClicked = $(this);
var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: TeamDetailPostBackURL,
contentType: "application/json; charset=utf-8",
data: { "Id": id },
datatype: "json",
success: function (data) {
$('#myModalContent').html(data);
$('#myModal').modal(options);
$('#myModal').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
});
});
</script>
Popup View
Edit.cshtml
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.AID)
<table>
<tr>
<td>#Html.LabelFor(model => model.Comment)</td>
<td>#Html.TextAreaFor(model => model.Comment, new { #class = "form-control", rows = "5" })</td>
</tr>
<tr>
<td><input type="submit" value="Save" class="btn btn-primary" id="btnSave"/></td>
<td><button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button></td>
</tr>
</table>
</div>
}
Controller
DatabaseController.cs
public ActionResult Index()
{
return View(db.ActionableEvents.ToList());
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ActionableEvents actionableEvents = db.ActionableEvents.Find(id);
if (actionableEvents == null)
{
return HttpNotFound();
}
return View(actionableEvents);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "AID,Comment")] ActionableEvents actionableEvents)
{
if (ModelState.IsValid)
{
db.Entry(actionableEvents).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(actionableEvents);
}
I did see this resource here: asp.net submit button close Jquery Ajax, but I'm just not seeing how I would be able to tweak this into what I've got going on right now.
The cancel button I have right now works perfectly. Is there some way to use data-dismiss for my submit button and have it still save the data like I have for the cancel button? I've also seen some solutions use an onClick() parameter in the submit button, but then it would use a window.close() option. I don't want the entire window to close, nor do I want the user to be prompted about it either.
What is a good way I can approach this problem? I want my submit button to work just like my cancel button, only save the data. Thanks in advance for any advice!!!
Can you try the following in your Index.cshtml (make sure you set an id for the form and correct it below):
$("form").submit(function(){
$('#modal').modal('toggle');
});
If you want to make an AJAX request to the server and save the data you can do as follows (just include the code below in a click event on the dismiss button from the modal):
$.ajax({
type: "POST",
url: "SaveData",
content: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(data),
success: function (result) {
// do something
},
error: function (result) {
// do something
}
});
And have a MVC action similiar to:
[HttpPost]
public JsonResult SaveData()
{
// save data
}
Edit:
After a second reading of your question, you need to make Edit.cshtml a partial view, then on Index.cshtml include your partial view in the div for the modal like this:
<div id="myModal" class="modal">
<div class="modal-dialog">
<div class="modal-content">
#Html.Partial("_EditView")
</div>
</div>
</div>
And your JS should look like this:
$("form").submit(function () {
e.preventDefault();
formData = $(this).serialize();
$.ajax({
type: "POST",
url: "SaveData",
content: "application/json; charset=utf-8",
dataType: "json",
data: formData ,
success: function (result) {
// do something
},
error: function (result) {
// do something
}
});
$('#modal').modal('toggle');
});
The JS should be in the Index.cshtml because that's where your partial exists, try it and you'll see.
So, after a lot of playing around, I was able to come up with the following solution:
View
Index.cshtml
<table>
#foreach (var item in Model)
<tr>
<td>
<button class="btn btn-primary" onclick="ActionAway(#item.AID)">Action Event</button>
</td>
</tr>
}
</tbody>
</table>
<div class="modal fade" id="myModal1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h3 class="modal-title">Action This Event</h3>
</div>
<div class="modal-body" id="myModalBodyDiv1">
</div>
</div>
</div>
</div>
</div>
<script>
var ActionAway = function (theid) {
var url = "/Database/Edit?id=" + theid;
$('#myModalBodyDiv1').load(url, function () {
$('#myModal1').modal("show");
})
}
</script>
Pop-up View
Edit.cshtml
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.AID)
<table>
<tr>
<td>#Html.LabelFor(model => model.Comment)</td>
<td>#Html.TextAreaFor(model => model.Comment, new { #class = "form-control", rows = "5" })</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save" class="btn btn-primary" id="btnSave"/>
<button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
</td>
</tr>
</table>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script>
$(document).ready(function () {
$("#btnSave").click(function () {
$.ajax({
success: function () {
$("#myModal").modal("hide");
}
})
})
})
</script>
The controller I was able to leave as it was without making any changes. Thanks again for all the help!

Passing and handling of varibles to a function with AJAX in MVC

I'm having trouble passing a variable into a function in my view. I'm fairly new to MVC and not sure how I save and pass information.
#model Models.Schedule.SheduleModel
#{
Layout = null;
}
<div>
<div class="tableRow">
<p>Make a schedule reminder.</p>
</div>
<div class="tableRow tableRowHeading">
<div class="row" style="width: 210px">Name</div>
<div class="row" style="width: 210px">Number</div>
</div>
#foreach (var shedule in Model.ScheduleList)
{
<div class="tableRow">
#using (Html.BeginForm("UpdateSchedule", "Schedule", FormMethod.Post))
{
<div class="cell" style="width: 210px">
#Html.HiddenFor(model => schedule.Id)
#Html.TextBoxFor(model => schedule.Name, new { #class = "inputFieldText" })
#Html.ValidationMessageFor(model => schedule.Name)
</div>
<div class="cell" style="width: 210px">
#Html.TextBoxFor(model => agent.ContactNumber, new { #class = "inputFieldText" })
#Html.ValidationMessageFor(model => agent.ContactNumber)
</div>
<div class="cell">
<button name="Update" type="submit" value="Update" class="button" title="Update details">
<span class="text">Update</span>
</button>
</div>
<div class="cell">
<button class="button" type="button" onclick="deleteFromSchedule();" value="Delete">
<span class="text">Delete</span>
</button>
</div>
}
</div>
}
</div>
#Scripts.Render("~/bundles/jqueryval")
<script>
function deleteFromSchedule() {
$.ajax(
{
type: 'POST',
url: urlBase + 'Schedule/UpdateSchedule/' + Id,
data:
{
Id: Id
},
success: function (data) {
console.log(data);
},
error: function () {
var errorMessage = 'Error occurred while sending message';
console.log(errorMessage);
}
});
}
}
</script>
I'm trying to pass the schedule Id in HiddenFor into the delete function but everything I try doesn't work, i'm also curious on how to handle the information gotten from the text box in a later unwritten div, I'd like to produce text on the screen saying
User #Model.Name and number #Model.Number will be notified of schedule change but I keep displaying blank spaces. an I use the form I'm creating for this information, what would the syntax be?. My method in the schedule controller is very straight forward.
[HttpPost]
public void UpdateSchedule(int Id)
{
////do stuff here
}
The simplest way is to add your id from the schedule into the inline function call (using razor), and add an id param into your javascript delete function:
<div class="cell">
<button class="button" type="button" onclick="deleteFromSchedule(#schedule.Id);" value="Delete">
<span class="text">Delete</span>
</button>
</div>
<script>
function deleteFromSchedule(id) {
$.ajax(
{
type: 'POST',
url: urlBase + 'Schedule/UpdateSchedule/' + id,
data:
{
Id: id
},
success: function (data) {
console.log(data);
},
error: function () {
var errorMessage = 'Error occurred while sending message';
console.log(errorMessage);
}
});
}
}
</script>

Show Json in same cshtml page using ajax after post

I'm working on a Search function, I'm returning a Json result from the Controller Action method. Everything is working fine, except that I want to show the results from the Action Method in the same Index page(my default page: http://localhost:51450/), but for some reason it routes to http://localhost:51450/Students/SearchStudent and in that page it just shows the result in json format: [{"StudentID":166,"Name":"ss","LastName":"s","Age":23}] and of course there is not any format in there. I'm using ajax with the purpose to show the results in the same Index page.. There should be something that I'm missing, what is it?
Controller Action Methods(1 just to show the view and the other to submit the filled form...):
public PartialViewResult SearchStudent()
{
return PartialView();
}
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult SearchStudent(string name)
{
List<Student> list = db.Students.Where(s => s.Name == name).ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
Partial View(The user should put a name and in then click submit):
#model Pedro2.Models.Student
using (#Html.BeginForm("SearchStudent", "Students", FormMethod.Post, new { #id = "formSearchStudent" }))
{
#Html.AntiForgeryToken()
<div class="form-group">
<div class="col-md-10">
#Html.LabelFor(model => model.Name)
#Html.TextBoxFor(model => model.Name)
</div>
</div>
<div class="form-group">
<input type="submit" value="Submit" id="submitSearch" data-url="#Url.Action("SearchStudent", "Students")" />
</div>
}
<div id="divResult"></div>
Index view(only the part concerning to this operation):
<p class="hand" id="pSearch" data-urlSearch="#Url.Action("SearchStudent","Students")"> Search by name</p>
<div id="ShowFormSearch"></div>
And the JQuery code:
$(function () {
$("#pSearch").click(function () {
ShowSearchPage();
return false;
})
$("#submitSearch").click(function () {
SearchStudent();
return false;
})
})
function SearchStudent() {
$.ajax({
type: 'get',
url: $("#submitSearch").data('url'),
data: $("#formSearchStudent").serialize + { name: $("#Name").val() },
datatype : 'json'
}).success(function (result) {
$("#divResult").html(result)
}).error(function () {
$("#divResult").html("An error occurred")
})
}
function ShowSearchPage()
{
$.ajax({
type: 'get',
url: $("#pSearch").data('urlsearch')
}).success(function (result) {
$("#ShowFormSearch").html(result)
}).error(function () {
$("#ShowFormSearch").html("An error occurred")
})
}
If you need to ask me anything just let me know

PartialView dosen't appear on click

I have trouble getting my partial view appear in the "div" when I click on a button. I can see that it fetches the data when I debug, but does not display it. Anybody that might now the problem?.
View
#model IEnumerable<ActiveDirectorySearch.Models.UserModel>
<div id="searchList">
<table>
#foreach (var user in #Model)
{
<tr>
<td>
<ul class="user" data-user-id="#user.DistinguishedName">
<li><b>#user.DisplayName</b></li>
<li><i>Cdsid:</i> #user.CdsId</li>
<li><i>Name:</i> #user.GivenName #user.SurName</li>
<li><i>Title:</i> #user.Title</li>
<li><i>Department:</i> #user.Department</li>
<li><i>MemberOf:</i> Groups</li>
<li class="userInfo">More Info</li>
<li>
</li>
</ul>
</td>
</tr>
}
</table>
<div class="col-md-6 col-md-offset-3 display-groups">
</div>
</div>
Controller
public ActionResult GetUserInfo(string searchTerm)
{
GroupRepository groupRepository = new GroupRepository();
var groups = groupRepository.FindGroups(searchTerm);
return PartialView(groups);
}
Script
<script>
$(function () {
$('.LoadGroupsViewButton').click(function () {
var self = this;
var $user = $(self).closest('.user');
var userDistinguisedName = $user.data("user-id");
$.ajax({
method: "GET",
url: 'Home/GetUserInfo',
data: { searchTerm: userDistinguisedName }
}).done(function (data) {
$(self).find('.display-groups').html(data);
});
});
});
</script>
change your code from
$(self).find('.display-groups').html(data);
to
$("#searchList").find('.display-groups').html(data);
as here 'self' is the DOM element that triggered the event because of this piece of code
var self = this;
So it will not find div having class 'display-groups'

Categories