The client-side validation in ASP.Net Core is not working. I have the following code:
#model VeoScheduling.Models.SignInModel
#{
ViewData["Title"] = "SignIn";
}
<div class="login">
<h2>Sign In</h2>
<div>
<form method="post" asp-action="SignIn">
<input type="hidden" asp-for="RedirectUrl" />
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input type="email"
data-bind="value: email" asp-for="Email"
class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password"
class="control-label"></label>
<input type="password" asp-for="Password"
data-bind="value: password"
class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Account</label>
<select name="accountSelected" style="margin:5px;width:200px"
data-bind='options: availableAccounts, optionsText: "value", optionsValue: "key", value: selectedAccount,event:{change: accountSelected()}'></select>
</div>
<br />
#if (Model.Error != "" || Model.Error != null)
{
<p style="color:red">#Html.Raw(Model.Error)</p>
}
</form>
</div>
</div>
#section Scripts{
<script>
var vModel = #Html.Raw(Json.Serialize(Model))
</script>
<script src="~/js/signIn.js" asp-append-version="true"></script>
}
I have also added javascript validation files and I can see they are being loaded when I run but still client-side validation is not working.
I have applied required attribute for both email and password filed. But client-side validation is still not working.
public class SignInModel
{
[Required(ErrorMessage ="Email is required")]
public string Email { get; set; }
[Required(ErrorMessage ="Password is required")]
public string Password { get; set; }
[DisplayName("Forgot Password")]
public bool ForgotPassword { get; set; }
public string RedirectUrl { get; set; }
public string Error { get; set; }
}
$(document).ready(function () {
self.vm = new viewModel(self.vModel);
ko.applyBindings(self.vm);
});
Below is the js code.
var viewModel = function (model) {
var self = this;
//properties
self.email = ko.observable('');
self.password = ko.observable('');
self.redirectUrl = model.redirectUrl;
self.availableAccounts = ko.observableArray(model.availableAccounts);
self.selectedAccount = ko.observable(null);
//events
self.signOn = function () {
var payloadData = {
'email': self.email(),
'password': self.password(),
'accountSelected': self.selectedAccount()
};
var url = window.location.origin + '/account/SignIn';
CallService("Post", url, payloadData)
.done(function (data) {
var url = window.location.origin + self.redirectUrl;
window.location.replace(url);
});
};
self.accountSelected = function (e, d) {
//alert(self.selectedStack());
};
//methods
self.forgotPassword = ko.observable(false);
self.resetPassword = function () {
$('#loader').show();
var payloadData = {
'email': self.email()
};
var url = window.location.origin + '/API/resetPassword'
$.post(url, payloadData)
.always(function () {
$('#loader').hide();
})
.fail(function (xhr, status, error) {
alert('resetPassword(): error' + xhr.responseText);
})
.done(function (data) {
alert("reset email sent.");
});
};
//ajax
self.getUsersAccounts = function () {
if (self.email() === "")
return;
var payloadData = {
'email': self.email()
};
var url = window.location.origin + '/API/GetAccountsByEmail';
CallService("GET", url, payloadData)
.done(function (data) {
self.availableAccounts.removeAll();
self.availableAccounts(data);
});
};
//computed
self.userChanged = ko.computed(function () {
var userID = self.email();
//alert(userID);
//console.log(userID);
self.getUsersAccounts();
});
self.forgotChecked = ko.computed(function () {
var checked = self.forgotPassword();
var email = self.email();
if (checked) {
if (email === '') {
alert("Please fill in email to reset password");
self.forgotPassword(false);
}
else {
alert("An email link will be sent to your email address.");
self.resetPassword();
self.forgotPassword(false);
}
}
});
//init
if (model.availableAccounts.length === 1) {
self.selectedAccount(model.availableAccounts[0].key);
}
};
$(document).ready(function () {
self.vm = new viewModel(self.vModel);
ko.applyBindings(self.vm);
});
you could try:
<form id="someform">
......
</form>
<script>
.....
if ($("#someform").valid())
{
//ajax codes
}
else {
return false;
}
</script>
also you could try:
var somevalue = document.getElementById("someId").value;
if (somevalue == null || somevalue == '')
{
$('#somespanId').html("*required");
return false;
}
Related
The problem:
I am trying to save events in a calendar by passing the content in ajax to my controller function. But I keep on getting null values being passed to my database. I have checked the console.log under Network tools in browsers and all of the data is null except EventId .
I know inserting the events into the database is working but it seems like the data being inserted is not being read by either Ajax or there's something wrong with my controller. Why do I keep on getting null values?
What the data in my database looks like after I saved the events
Here's my controller
[HttpPost]
public IActionResult SaveEvent(Event data)
{
var userId = _userManager.GetUserId(User);
var status = false;
if (string.IsNullOrEmpty(userId))
{
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { Data = false, ErrorMessage = "no User Id!" });
}
if (data.EventId > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventId == data.EventId).FirstOrDefault();
if (v != null)
{
userId = data.UserId;
v.EventId = data.EventId;
v.Title = data.Title;
v.Counselor = data.Counselor;
v.Description = data.Description;
v.EventStart = data.EventStart;
v.EventEnd = data.EventEnd;
v.AllDay = data.AllDay;
v.ThemeColor = data.ThemeColor;
}
}
else
{
db.Events.Add(data);
}
db.SaveChanges();
status = true;
return Json(new { Data = data, status});
}
This is my Event class:
public class Event {
public string UserId { get; set; }
public int? EventId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string EventStart { get; set; }
public string EventEnd { get; set; }
public string Counselor { get; set; }
public string ThemeColor { get; set; }
public bool AllDay { get; set; }
}
and my Ajax function
function GenerateCalender(events) {
jq341('#calender').fullCalendar('destroy');
jq341('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events: events,
eventClick: function (calEvent, jsEvent, view) {
selectedEvent = calEvent;
jq341('#myModal #eventTitle').text(calEvent.title);
var description = jq341('<div />');
description.append(jq341('<p />').html('<b>Start:</b>' + calEvent.start.format("DD-MMM-YYYY HH:mm a")));
if (calEvent.end != null) {
description.append(jq341('<p/>').html('<b>End:</b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
}
description.append(jq341('<p />').html('<b>Description:</b>' + calEvent.description));
jq341('#myModal #pDetails').empty().html(description);
jq341('#myModal').modal();
},
selectable: true,
select: function (start, end) {
selectedEvent = {
userID: '',
eventID: 0,
title: '',
counselor: '',
start: start,
end: end,
description: '',
allDay: false,
color: ''
};
openAddEditForm();
jq341('#calendar').fullCalendar('unselect');
},
editable: true,
eventDrop: function (event) {
var data = {
UserId: event.userID,
EventId: event.eventID,
Title: event.title,
Counselor: event.counselor,
EventStart: event.start.format('DD/MM/YYYY HH:mm A'),
EventEnd: event.end != null ? event.end.format('DD/MM/YYYY HH:mm A') : null,
Description: event.description,
AllDay: event.allDay,
ThemeColor: event.color,
};
SaveEvent(data);
}
})
}
function openAddEditForm() {
if (selectedEvent != null) {
jq341('#hdEventID').val(selectedEvent.eventID);
jq341('#hdUserID').val(selectedEvent.userID);
jq341('#txtSubject').val(selectedEvent.title);
jq341('#ddCounselor').val(selectedEvent.counselor);
jq341('#txtStart').val(selectedEvent.start.format('DD/MM/YYYY HH:mm A'));
jq341('#chkIsFullDay').prop("checked", selectedEvent.allDay || false);
jq341('#chkIsFullDay').change();
jq341('#txtEnd').val(selectedEvent.end != null ? selectedEvent.end.format('DD/MM/YYYY HH:mm A') : '');
jq341('#txtDescription').val(selectedEvent.description);
jq341('#ddThemeColor').val(selectedEvent.color);
}
jq341('#myModal').modal('hide');
jq341('#myModalSave').modal();
}
jq341('#btnSave').click(function () {
//Validation
if (jq341('#txtSubject').val().trim() == "") {
alert('Title required');
return;
}
if (jq341('#txtStart').val().trim() == "") {
alert('Start date required');
return;
}
if (jq341('#chkIsFullDay').is(':checked') == false && jq341('#txtEnd').val().trim() == "") {
alert('End date required');
return;
}
else {
var format_start = jq341('#txtStart').val().replace(' ', '-').split('-');
var nowy_start = format_start[1] + '-' + format_start[0] + '-' + format_start[2] + ' ' + format_start[3];
var format_end = jq341('#txtEnd').val().replace(' ', '-').split('-');
var nowy_end = format_end[1] + '-' + format_end[0] + '-' + format_end[2] + ' ' + format_end[3];
}
//edited
var data = {
UserId: jq341('#hdUserID').val(),
EventId: jq341('#hdEventID').val(),
Title: jq341('#txtSubject').val().trim(),
Counselor: jq341('#ddCounselor').val(),
EventStart: jq341('#txtStart').val().trim(),
EventEnd: jq341('#chkIsFullDay').is(':checked') ? null : jq341('#txtEnd').val().trim(),
Description: jq341('#txtDescription').val(),
ThemeColor: jq341('#ddThemeColor').val(),
AllDay: jq341('#chkIsFullDay').is(':checked')
}
alert(data);
SaveEvent(data);
// call function for submit data to the server
})
function SaveEvent(data) {
jq341.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
url: '/Calendar/SaveEvent',
data: JSON.stringify(data),
success: function (data) {
console.log(data)
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
jq341('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed', ErrorMessage);
}
})
}
my cshtml
<div id="myModalSave" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Appointments</h4>
</div>
<div class="modal-body">
<form class="col-md-12 form-horizontal">
<input type="text" id="hdEventID" value="0" />
<input type="hidden" id="hdUserID">
<div class="form-group">
<label>Subject</label>
<input type="text" id="txtSubject" class="form-control" />
</div>
<div class="form-group">
<label>Counselor</label>
<select id="ddCounselor" class="form-control">
<option value="0">Choose your counselor</option>
<option value="DrSalwa">Dr Salwa</option>
<option value="DrNorzaiham">Dr Norzaiham</option>
<option value="Nasri">Sir Nasri</option>
<option value="Adibah">Ms. Adibah</option>
</select>
</div>
<div class="form-group">
<label>Start</label>
<div class="input-group date" id="dtp1">
<input type="text" id="txtStart" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label><input type="checkbox" id="chkIsFullDay" checked="checked" /> Is Full Day event</label>
</div>
</div>
<div class="form-group" id="divEndDate" style="display:none">
<label>End</label>
<div class="input-group date" id="dtp2">
<input type="text" id="txtEnd" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<label>Description</label>
<textarea id="txtDescription" rows="3" class="form-control"></textarea>
</div>
<div class="form-group">
<label>Theme Color</label>
<select id="ddThemeColor" class="form-control">
<option value="">Default</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
<option value="green">Green</option>
</select>
</div>
<button type="button" id="btnSave" class="btn btn-success">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
Below are screenshots of the Network tool
Using [FormBody] but getting that null exception in if(data.eventId >0) in controller
Below is [FormBody] is omitted from the controller but still getting null values except EventId
First, you should add the [FromBody] attribute, otherwise the data will not be successfully obtained.
You can add a breakpoint in your action to observe whether the binding is successful.
Then, modify your db.Add() method, because your data contains EventId, and in your database I see EventId as the primary key, and your primary key is auto-incremented. If you add a New entity of EventId, then an exception will be thrown.
You can try change your action like below:
[HttpPost]
public IActionResult SaveEvent([FromBody]Event data)
{
var userId = _userManager.GetUserId(User);
var status = false;
if (string.IsNullOrEmpty(userId))
{
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { Data = false, ErrorMessage = "no User Id!" });
}
if (data.EventId > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventId == data.EventId).FirstOrDefault();
if (v != null)
{
userId = data.UserId;
v.EventId = data.EventId;
v.Title = data.Title;
v.Counselor = data.Counselor;
v.Description = data.Description;
v.EventStart = data.EventStart;
v.EventEnd = data.EventEnd;
v.AllDay = data.AllDay;
v.ThemeColor = data.ThemeColor;
}
}
else
{
var data1 = new Event
{
UserId=data.UserId,
Title = data.Title,
Counselor = data.Counselor,
Description = data.Description,
EventStart = data.EventStart,
EventEnd = data.EventEnd,
AllDay = data.AllDay,
ThemeColor = data.ThemeColor,
};
db.Events.Add(data1);
}
db.SaveChanges();
status = true;
return Json(new { Data = data, status});
}
When I try to send a variable to JSON on ASP.net MVC, I am getting error like below:
jquery-2.2.3.min.js:4 GET http://localhost:58525/Order/GetAddress/?userid=42&email=asandtsale%40gmail.com 500 (Internal Server Error)
My controller:
public JsonResult GetAddress(int uservalue, string email)
{
UserService rpuser = new UserService();
DATA.Models.ORM.Entity.UserEntity.User userentity = rpuser.FirstOrDefault(x => x.Id == uservalue);
Models.DTO.OrderDTO.NewAddressVM addressmodel = new Models.DTO.OrderDTO.NewAddressVM();
addressmodel.FirstName = userentity.Name;
return Json(addressmodel.FirstName, JsonRequestBehavior.AllowGet);
}
View:
<script>
$(document).ready(function () {
$("#okbutton").click(function () {
var e = document.getElementById("emailadd");
var uservalue = e.options[e.selectedIndex].value;
var usertext = e.options[e.selectedIndex].text;
var link = "/Order/GetAddress/";
$.ajax({
type: "GET",
url: link,
data: {userid: uservalue, email: usertext},
success: function (result) {
if (result == "accept") {
$("div#voucher-result").html('<span style="color:green; font-weight:bold;">Your voucher code is valid. Discount price: <text style="font-size:19px;">£50</text><br />If you complete your order you will get a discount of £50.</span>');
} else {
$("div#voucher-result").html('<span style="color:green; font-weight:bold;">Your voucher code is valid. Discount price: <text style="font-size:19px;">£50</text><br />Else</span>');
}
}
});
});
});
And Form:
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Customer</label>
#Html.DropDownListFor(x => x.CustomerId, new SelectList(Model.CustomerList, "Id", "UserName"), new { #class = "form-control select2", #id="emailadd", #placeholder = "" })
</div>
</div>
<div class="col-md-6">
<label></label>
<button type="button" class="btn btn-block btn-success" id="okbutton" style="width:60px;">OK</button>
</div>
<div id="voucher-result"></div>
</div>
GetAddress(int uservalue, string email) expects a parameter called uservalue but in your javascript you are sending over an userid: data: {userid: uservalue, email: usertext}
You should change the parameter uservalue to userid in your controller or change userid to uservalue in your javascript.
I'm having a basic form with few text fields and a file upload controller on a bootstrap modal dialog (Bootstrap 4). below is my code:
Model:
public class DemoContent
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[RegularExpression("([0-9]+)",ErrorMessage = "Age must be numbers only")]
public int Age { get; set; }
[EmailAddress]
public string Email { get; set; }
[DataType(DataType.Upload)]
[Display(Name = "Image")]
public HttpPostedFileBase ImageUrl { get; set; }
}
JavaScript
$(function() {
$("a[data-modal=demoPopup]").on("click", function () {
$("#demoModalContent").load(this.href, function () {
$("#demoModal").modal({ keyboard: true }, "show");
$("#demoForm").submit(function () {
if ($("#demoForm").valid()) {
var files = $("ImageUrl").get(0).files;
var data = $(this).serialize();
data.append("ImageUrl", files[0]);
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$("#demoModal").modal("hide");
location.reload();
} else {
$("#MessageToClient").text(result.message);
}
},
error: function () {
$("#MessageToClient").text("The web server had an error.");
}
});
return false;
}
});
});
return false;
});
Controller:
[HttpPost]
public ActionResult Create(DemoContent model)
{
if (model.Age > 55)
{
var file = model.ImageUrl;
return Json(new { success = true });
}
else
{
return Json(new { success = false,message="Invalid Data" });
}
}
Now when i open the popup it works also when i submit the form it goes to the controller along with the file. but the problem is once the server returns the success message the popup shows that message in a blank page instead of capturing it and refreshing the current page or showing the messages. any idea why is this happening.
link to source files : https://drive.google.com/open?id=1W3H3kFEpHJWfaf7_UnJI3O5I900GxyC7
May be you wrote your javascripts function in document.ready() function,That is why it again refreshing.
Write your JavaScript code as follows:
$(function() {
$("a[data-modal=demoPopup]").on("click", function () {
$("#demoModalContent").load(this.href, function () {
$("#demoModal").modal({ keyboard: true }, "show");
$("#demoForm").submit(function (event) { // Pass the event as parameter to the function.
event.preventDefault(); // I have added these two lines
event.stopImmediatePropagation();
if ($("#demoForm").valid()) {
var files = $("ImageUrl").get(0).files;
var data = $(this).serialize();
data.append("ImageUrl", files[0]);
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$("#demoModal").modal("hide");
location.reload();
} else {
$("#MessageToClient").text(result.message);
}
},
error: function () {
$("#MessageToClient").text("The web server had an error.");
}
});
return false;
}
});
});
return false;
});
I think you should install and use Microsoft.Unobtrusive.Validation and *.Ajax, if you want your modal to be updated (I get your question like that...). With this, you can use code like the following example, which can update your modal (used this in a project a few days ago):
Modal:
#using (Ajax.BeginForm("Login", new { Controller = "Home", area = "" }, new AjaxOptions() { OnSuccess = "onSuccessLogin", HttpMethod = "POST", UpdateTargetId = "loginmodalbody"}, new { id = "loginForm" }))
{
<div class="modal-body" id="loginmodalbody">
<div class="text-danger loginfailed"></div>
<div class="container">
<div class="card border-primary mb-3" style="margin: 0 auto;">
<div class="card-body">
#Html.Partial("~/Views/Shared/Modals/LoginModalBody.cshtml")
</div>
</div>
<div class="container">
<span><a onclick="alert('Leads to pw info')" href="#">Forgot password?</a></span>
</div>
<br />
<button class="btn btn-primary btn-block buttonlogin">Login</button>
</div>
<br />
</div>
}
Modal Body:
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-lg-12 col-12">
#Html.EditorFor(model => model.EMail, new { htmlAttributes = new { #class = "form-control", placeholder = "EMail", #id = "inputemail" } })
#Html.ValidationMessageFor(model => model.EMail, "", new { #class = "text-danger", #id = "dangeremail" })
</div>
</div>
<div class="form-group">
<div class="col-lg-12 col-12">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control", placeholder = "Passwort", #id = "inputpassword" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger", #id = "dangerpassword" })
</div>
</div>
</div>
Thus, it updates your modal body after getting data from the posting of the form - you define the id to be updated within the AjaxOptions, as shown in the above snippet.
I'm trying to save the image on the server alongside with some information about it using form and then angular (1.5.7) and C#.
I've tried multiple ways, Either the file passed to Api controller is empty or the Model state is invalid.
Can you tell me what am I doing wrong?
My C# Controller:
namespace xxx.Controllers.Api
{
[Route("api/partners")]
public class PartnersController : Controller
{
private IMeblatRepository _repository;
private ILogger<PartnersController> _logger;
private IHostingEnvironment _environment;
public PartnersController(IMeblatRepository repository, ILogger<PartnersController> logger, IHostingEnvironment environment)
{
_repository = repository;
_logger = logger;
_environment = environment;
}
[HttpGet("")]
public IActionResult Get()
{
try {
var results = _repository.GetAllPartners();
return Ok(Mapper.Map<IEnumerable<PartnersViewModel>>(results));
}
catch (Exception ex)
{
_logger.LogError($"Failed to get All Partners: {ex}");
return BadRequest("Bad Request");
}
}
[HttpPost("")]
public async Task<IActionResult> Post([FromBody]Data data)
{
if (ModelState.IsValid)
{
var uploads = Path.Combine(_environment.WebRootPath, "uploads");
if (data.file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(uploads, data.file.FileName), FileMode.Create))
{
await data.file.CopyToAsync(fileStream);
}
}
//Save to the Database
var newPartner = Mapper.Map<Partners>(data.newPartner);
_repository.AddPartner(newPartner);
if(await _repository.SaveChangesAsync())
{
return Created($"api/partners/{data.newPartner.Name}", Mapper.Map<PartnersViewModel>(newPartner));
}
else
{
return BadRequest("Failed to save to the database");
}
}
return BadRequest(ModelState);
}
[HttpDelete("{name}")]
public async Task<IActionResult> Delete([FromRoute] string name)
{
if (ModelState.IsValid)
{
var partnerToDelete = _repository.GetPartnerByName(name);
_repository.RemovePartner(partnerToDelete);
if (await _repository.SaveChangesAsync())
{
return Ok($"api/partners");
}
else
{
return BadRequest("Failed to remove");
}
}
return BadRequest(ModelState);
}
}
}
Data class:
public class Data
{
public PartnersViewModel newPartner { get; set; }
public IFormFile file { get; set; }
}
Angular controller:
(function () {
"use strict";
// getting the existing module
angular.module("app-edit")
.controller("partnersController", partnersController);
function partnersController($http, $scope) {
var vm = this;
vm.partners = [];
vm.newPartner = {};
vm.errorMessage = "";
vm.isBusy = true;
var f = null;
$scope.add = function () {
f = document.getElementById('uploader').files[0];
if (f) {
alert("File attached succesfully");
}
};
$http.get("/api/partners").then(function (response) {
//success
angular.copy(response.data, vm.partners);
}, function () {
//failure
vm.errorMessage = "failed to load data";
})
.finally(function () {
vm.isBusy = false;
});
vm.addPartner = function () {
vm.isBusy = true;
vm.errorMessage = "";
var Indata = { 'newPartner': vm.newPartner, 'file': f };
$http.post("/api/partners", Indata)
.then(function () {
//success
vm.partners.push(response.data);
vm.newPartner = {};
}, function () {
//failure
vm.errorMessage = "Failed to save new partner";
})
.finally(function () {
vm.isBusy = false;
});
};
vm.removePartner = function (name) {
vm.isBusy = true;
vm.errorMessage = "";
$http.delete("/api/partners/" + name)
.then(function () {
//success
//vm.partners.shift();
//vm.newPartner = {};
vm.errorMessage = "Udało się usunąć partnera";
}, function () {
//failure
vm.errorMessage = "Nie udało się usunąć partnera";
})
.finally(function () {
vm.isBusy = false;
});
};
}
})();
HTML file:
<div class="col-md-6 col-md-offset-3">
<div class="text-danger" ng-show="vm.errorMessage">{{ vm.errorMessage }}</div>
<wait-cursor ng-show="vm.isBusy"></wait-cursor>
<form novalidate name="newPartnerForm" method="POST" enctype="multipart/form-data" ng-submit="vm.addPartner()">
<div class="form-group">
<label for="name">Nazwa Partnera</label>
<input class="form-control" type="text" id="name" name="name" ng-model="vm.newPartner.name" required/>
<span ng-show="newPartnerForm.name.$error.required" class="text-warning">To pole jest wymagane</span>
</div>
<div class="form-group">
<label for="files">Ścieżka</label>
<input type="file" id="uploader" name="files[]" class="btn btn-primary" accept="image/*" ng-model="files" ngf-multiple="false">
<button ng-click="add()">Add</button>
</div>
<div class="form-group">
<label for="href">Link do strony partnera</label>
<input class="form-control" type="text" id="href" name="href" ng-model="vm.newPartner.href"/>
</div>
<div class="form-group">
<input type="submit" value="Add"
class="btn btn-success btn-sm"
ng-disabled="newPartnerForm.$invalid" />
</div>
</form>
<table class="table table-responsive table-striped">
<tr ng-repeat="partner in vm.partners">
<td> {{partner.name}}</td>
<td> {{partner.href}}</td>
<td><a ng-href="#/editor/{{ patner.name }}" class="btn btn-sm btn-primary">Manage</a></td>
<td><input type="button" ng-click="vm.removePartner(partner.name)" value="Usuń" class="btn btn-sm btn-danger"/></td>
</tr>
</table>
Passing from form seems to be working as the alert is trigerred everytime I choose the file.
How can i get value from ajax to mvc controller method in 'FileStreamResult' in mvc?I want to pass value from #Model[i].ToString() to controller by ajax.
Controller
public ActionResult Index()
{
IEnumerable<VmFile> model = _manager.fileName();
return View(model);
}
public ActionResult Upload(HttpPostedFileBase file)
{
try
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/File/"), fileName);
file.SaveAs(path);
_manager.UploadFile(file, path.ToString());
}
ViewBag.Message = "Upload successful";
return RedirectToAction("Index");
}
catch
{
ViewBag.Message = "Upload failed";
return RedirectToAction("Index");
}
}
public FileStreamResult GetFile(int Id)
{
string fileName = _manager.FileName(Id);
string filePath = ConfigurationManager.AppSettings["FilePath"] + fileName;
FileStream fs = new FileStream(Server.MapPath(filePath), FileMode.Open, FileAccess.Read);
return File(fs, "application/pdf");
}
FileManager
public string FileName (int id)
{
string fileName = _unitOfWork.FileRepository.Get(r => r.Id == id).Select(f => f.Name).First();
return fileName;
}
public IEnumerable<VmFile> fileName()
{
var file = _unitOfWork.FileRepository.Get();
var model = from r in file
select new VmFile
{
Id = r.Id,
Name = r.Name,
ThanaId =r.ThanaId,
RoadId = r.RoadId,
Url = r.Url,
UpLoadDate = r.UpLoadDate,
FCategoryId = r.FCategoryId,
FileType = r.FileType
};
return model;
}
public void UploadFile(HttpPostedFileBase file,string path)
{
string fName = file.FileName;
string[] typ = fName.Split('.');//Regex.Split(fName, #".");
File newFIle = new File
{
Name = fName,
Url = path,
FCategoryId = 1,
ThanaId = 23201,
RoadId = 12,
FileType = typ[1],
UpLoadDate = DateTime.Now
};
_unitOfWork.FileRepository.Insert(newFIle);
_unitOfWork.Save();
}
VmFile
public class VmFile
{
public int Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public Nullable<short> BridgeId { get; set; }
public Nullable<DateTime> UpLoadDate { get; set; }
public Nullable<double> FromChain { get; set; }
public Nullable<double> ToChain { get; set; }
public string FileType { get; set; }
public Nullable<int> FCategoryId { get; set; }
public Nullable<int> ThanaId { get; set; }
public Nullable<int> RoadId { get; set; }
}
View
#model IEnumerable<RSDMS.ViewModel.VmFile>
#{
Layout = null;
}
<html>
<head>
<link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="header" class="container">
<h2>Document Module</h2>
<div class="panel panel-default">
<div id="h2" class=" panel panel-primary "><h4 id="h4">Document Type</h4></div>
<div id="form" class=" panel-body">
<form role="form">
<label class="checkbox-inline">
<input type="checkbox" value="">A-Road Related
</label>
<label class="checkbox-inline">
<input type="checkbox" value="">B-Road+Structure Relate
</label>
<label class="checkbox-inline">
<input type="checkbox" value="">C-
</label>
<label class="checkbox-inline">
<input type="checkbox" value="">Option 1
</label>
<label class="checkbox-inline">
<input type="checkbox" value="">Option 2
</label>
<label class="checkbox-inline">
<input type="checkbox" value="">Option 3
</label>
</form>
</div>
</div>
<div id="listpanel" class="panel-primary">
<h1>List Panel</h1>
<div id="file">
<table>
<th>File Name</th>
#foreach (var file in Model)
{
<tr>
<td>
<li>
#file.Name
</li>
</td>
</tr>
<br />
}
</table>
</div>
#using (Html.BeginForm("Upload", "Document", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
<label class="btn btn-block btn-primary">
Browse … <input type="file" name="file" id="file" style="display: none;">
</label>
<input type="submit" class="btn" value="Upload">
}
</div>
<div id="frame" class="panel-body">
<div id="frame">
<iframe src="#Url.Action("GetFile", "Document")" width="900px" height="500px"></iframe>
</div>
</div>
</div>
</body>
</html>
<style>
#h2 {
background-color: lightblue;
height: 40px;
}
#h4 {
margin-left: 20px;
}
#header {
margin-left: 50px;
margin-right: 50px;
}
#frame {
float: right;
margin-bottom: 50px;
}
#listpanel {
float: left;
}
</style>
<script>
$(document).ready(function(e) {
// var p = { Data: $('#fileId').val() };
//var currentDataItem = this.dataItem(this);
//id = currentDataItem.Id;
alert($('#fileId').attr('id'));
var p = { Data: $('#fileId').val() };
alert(p);
var id = $('#fileId').text();
alert(id);
$('#fileId').click(function () {
$.ajax(
{
//url: '#Url.Action("GetFile", "Document")?id=' + id,
url: '/Document/GetFile',
type: "POST",
data: {Id:id},
success:function(data)
{
},
error:function(e)
{
}
});
})
});
</script>
Your javascript code should be wrapped in a jQuery load function, like this:
$(function () {
//Paste all your java script here
});
That was the only change I made on my side and the AJAX call to GetFile in the Document controller is now working
As Denis Wessels said you have to enclose jquery code inside document ready block
$( document ).ready(function() {
var currentDataItem = this.dataItem(this.select());
id = currentDataItem.Id;
var p = { Data: $('#fileId').val() };
$('#fileId').click(function () {
$.ajax(
{
url: '#Url.Action("GetFile", "Document")?id=' + id,
//url: '/Document/GetFile',
type: "POST",
// data: {Id:id},
success:function(data)
{
},
error:function(e)
{
}
});
})
});
First all let me correct certain mistakes in your code. In view haven't passed any id that could be passed in the action method. So either in the FileManager class change the returntype of GetData method as
Dictionary<int,string>
OR
create a model class say FileManagerModel as follows
public class FileManagerModel
{
public int ID {get;set;}
public string FileName{get;set;}
}
and change the return type as
List<FileManagerModel>
accordingly change the model in the view as
#model Dictionary<int, string> // If the return type is Dictionary<int,string>
and then in the view change your for loop as follows
#foreach(var file in Model)
{
<tr>
<td>
<li>
#file.Value
</li>
</td>
</tr>
<br />
}
and also change your GetFile method as follows
public FileStreamResult GetFile(int? id)
{
string fileName = "IFrameTest.txt";
var t = ConfigurationManager.AppSettings["FilePath"];
string filePath = ConfigurationManager.AppSettings["FilePath"] + fileName;
FileStream fs = new FileStream(Server.MapPath(filePath), FileMode.Open, FileAccess.Read);
return File(fs, "text/plain");
}
add nullable int arguement in your method as on page load your id will be null.
As the method by default is HTTPGET method in your Ajax call you need to make changes as follows
<script>
$(document).ready(function(e) {
var id = $('#fileId').text();
$('#fileId').click(function (event) {
event.preventDefault();
var id = $(this).data("id");
$.ajax(
{
url: '#Url.Action("GetFile", "Document")',
type: "GET",
data: { id: id },
success:function(data)
{
},
error:function(e)
{
}
});
})
});
</script>
On doing these changes it worked for me .I hope this will rectify your issue
UPDATE
If you are using IEnumerable pass the Id in the data attribute as
#file.Name