I am trying to add an editing function to a DB record that a user submitted. The thing is, that there is a picture (as byte) in the mix. The picture has previously been cropped (mainly for styling reasons) and of course, a user would need to have the option to a) keep the existing picture or b) select and crop a new picture. The following code works fine if a user submits a new picture, but in case there is no new picture, it would override the existing one instead of keeping the one the user previously uploaded.
Here's my controller:
// POST: EditErrand
public ActionResult UpdateErrand([Bind(Exclude = "Picture")]EditErrandsViewModel model)
{
string newPic = Request.Form["editErrandCroppedPicture"];
byte[] imageBytes = Convert.FromBase64String(newPic);
var userId = User.Identity.GetUserId();
var errand = new EditErrandsViewModel
{
ID = model.ID,
UserID = User.Identity.GetUserId(),
FirstName = UserManager.FindById(userId).FirstName,
Email = UserManager.FindById(userId).Email,
Phone = UserManager.FindById(userId).PhoneNumber,
Hometown = UserManager.FindById(userId).Hometown,
Rating = model.Rating,
Category = model.Category,
SubCategory = model.SubCategory,
Title = model.Title,
Description = model.Description,
Location = model.Location,
ASAP = model.ASAP,
StartDateTime = model.StartDateTime,
DurationInHours = model.DurationInHours,
EndDateTime = model.EndDateTime,
DateTimePosted = DateTime.UtcNow.ToUniversalTime(),
Currency = model.Currency,
Offering = model.Offering,
Price = model.Price,
errandTax = model.errandTax,
PaymentMethod = model.PaymentMethod,
LatitudePosted = model.LatitudePosted,
LongitudePosted = model.LongitudePosted,
LocationPosted = model.LocationPosted,
UserActivityLatitude = model.LatitudePosted,
UserActivityLongitude = model.LongitudePosted,
UserActivityLocation = model.LocationPosted,
Published = false
};
if (imageBytes.Length > 2)
{
errand.Picture = imageBytes;
}
DB.Entry(errand).State = EntityState.Modified;
DB.SaveChanges();
var Success = new UserActivities
{
ActivityName = "EditErrand_Success",
UserID = User.Identity.GetUserId(),
ActivityTimeStamp = DateTime.Now.ToUniversalTime(),
ActivityLatitude = model.UserActivityLatitude,
ActivityLongitude = model.UserActivityLongitude,
ActivityLocation = model.UserActivityLocation
};
DB.UserActivityList.Add(Success);
DB.SaveChanges();
return RedirectToAction("errandPreview");
}
The controller has the following statement in there because if a user does not upload a file, it would still write 0x to the DB.
if (imageBytes.Length > 2)
{
errand.Picture = imageBytes;
}
For the sake of completeness I have added the relevant part of the view as well, so you get an idea on how cropping (using JCrop) is done:
<div id="editErrandPictureDisplay" class="errandomDisplay col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-4 col-md-7 col-lg-offset-5 col-lg-6">
<img id="editErrandPicture" class="editErrandPicture" src="#Url.Action("errandPicture", "errandom")" />
</div>
<div id="editErrandPictureArea" class="manageArea row">
#Html.LabelFor(m => m.Picture, new { #id = "editErrandPictureLabel", #class = "manageLabel col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-1 col-md-3 col-lg-offset-1 col-lg-4" })
<a id="editErrandPictureSelectionButton" class="manageField col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-0 col-md-7 col-lg-offset-0 col-lg-6" href="#">
select a file...
</a>
#Html.TextBoxFor(m => m.Picture, new { #id = "editErrandPictureField", #class = "manageField col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-0 col-md-7 col-lg-offset-0 col-lg-6", #type = "file", #style = "display: none" })
</div>
<hr />
<script>
jQuery("#editErrandPictureSelectionButton").click(function () {
$("#editErrandPictureField").click();
$("#editErrandCroppingArea").show();
});
</script>
<script>
$("#editErrandPictureField").change(function () {
var fullFileName = $("#editErrandPictureField").val()
$("#editErrandPictureSelectionButton").html(fullFileName.substr(fullFileName.lastIndexOf('\\') + 1));
});
</script>
<div id="editErrandCroppingArea" class="manageArea row" style="display: none">
<img id="editErrandOriginal" class="editErrandImage" src="" alt="" style="display: none" />
<canvas id="editErrandCropped" class="editErrandImage" height="5" width="5"></canvas>
<input id="editErrandButtonCrop" class="manageButton col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-1 col-md-10 col-lg-offset-1 col-lg-10" type="button" value="Crop" />
<input id="editErrandCropX" class="editErrandData" name="editErrandCropX" type="hidden" />
<input id="editErrandCropY" class="editErrandData" name="editErrandCropY" type="hidden" />
<input id="editErrandCropW" class="editErrandData" name="editErrandCropW" type="hidden" />
<input id="editErrandCropH" class="editErrandData" name="editErrandCropH" type="hidden" />
<input id="editErrandCroppedPicture" class="editErrandData" name="editErrandCroppedPicture" type="hidden" />
</div>
<script type="text/javascript">
$(function () {
if ($('#editErrandCroppingArea').width() > 500) {
$('#editErrandPictureField').change(function () {
$('#editErrandOriginal').hide();
var reader = new FileReader();
reader.onload = function (e) {
$('#editErrandOriginal').show();
$('#editErrandOriginal').attr("src", e.target.result);
$('#editErrandOriginal').Jcrop({
onChange: SetCoordinates,
onSelect: SetCoordinates,
aspectRatio: 1,
boxWidth: 450,
addClass: 'editErrandCropping'
});
}
reader.readAsDataURL($(this)[0].files[0]);
});
}
else {
$('#editErrandPictureField').change(function () {
$('#editErrandOriginal').hide();
var reader = new FileReader();
reader.onload = function (e) {
$('#editErrandOriginal').show();
$('#editErrandOriginal').attr("src", e.target.result);
$('#editErrandOriginal').Jcrop({
onChange: SetCoordinates,
onSelect: SetCoordinates,
aspectRatio: 1,
boxWidth: 250,
addClass: 'editErrandCropping'
});
}
reader.readAsDataURL($(this)[0].files[0]);
});
}
$('#editErrandButtonCrop').click(function () {
var x1 = $('#editErrandCropX').val();
var y1 = $('#editErrandCropY').val();
var height = $('#editErrandCropH').val();
var width = $('#editErrandCropW').val();
var canvas = $("#editErrandCropped")[0];
var context = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
canvas.height = height;
canvas.width = width;
context.drawImage(img, x1, y1, width, height, 0, 0, width, height);
var image = canvas.toDataURL().replace(/^data:image\/[a-z]+;base64,/, "");
$('#editErrandCroppedPicture').val(image);
//$('#editErrandButtonUpload').show();
$('#editErrandCropped').hide();
$('#editErrandButtonCrop').hide();
};
img.src = $('#editErrandOriginal').attr("src");
});
});
function SetCoordinates(c) {
$('#editErrandCropX').val(c.x);
$('#editErrandCropY').val(c.y);
$('#editErrandCropW').val(c.w);
$('#editErrandCropH').val(c.h);
$('#editErrandButtonCrop').show();
};
</script>
So ultimately my question is:
How can I update the picture if a user selects a new one (which works fine) AND make sure the previously uploaded picture is not overridden if a user does not select a new picture? Right now, all values would be updated except for the picture (unless a new picture is selected and cropped).
Now after adding a View Model, I get the following error:
The entity type EditErrandViewModel is not part of the model for the current context.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:
System.InvalidOperationException: The entity type EditErrandViewModel is not part of the model for the current context.
Source Error:
Line 348: errand.Picture = imageBytes;
Line 349: }
Line 350: DB.Entry(errand).State = EntityState.Modified;
Line 351: DB.SaveChanges();
Line 352: var Success = new UserActivities
Related
I try to convert this simple google apps script code below to HTML services code. The code below is written with the deprecated google apps script UI services! Could anyone please help me with HTML services example code in this usecase?
I'm not really sure how to approach it as I haven't been coding for too long.
A little bit of help would be very much appreciated.
Thanks!!
Mireia
function() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication();
app.setHeight(400);
var scriptProps = PropertiesService.getScriptProperties();
var label1 = app.createLabel('XERO Settings').setStyleAttribute('font-weight', 'bold').setStyleAttribute('padding', '5px').setId('label1');
var panel1 = app.createVerticalPanel().setId('panel1');
var grid = app.createGrid(7, 2);
var absPanel = app.createAbsolutePanel();
var handler = app.createServerHandler('saveSettings');
var clientHandler1 = app.createClientHandler();
var clientHandler2 = app.createClientHandler();
var clientHandler3 = app.createClientHandler();
var btnSave = app.createButton('Save Settings', handler);
var lblAppType = app.createLabel('Application Type: ');
var appTypes = {Private:0, Public:1, Partner:2};
var listAppType = app.createListBox().setName('appType').addItem('Private').addItem('Public').addItem('Partner').addChangeHandler(clientHandler1).
addChangeHandler(clientHandler2).addChangeHandler(clientHandler3).setSelectedIndex(appTypes[(scriptProps.getProperty('appType') != null ? scriptProps.getProperty('appType'): 'Private')]);
handler.addCallbackElement(listAppType);
var lblAppName = app.createLabel('Application Name: ');
var txtAppName = app.createTextBox().setName('userAgent').setWidth("350")
.setValue((scriptProps.getProperty('userAgent') != null ? scriptProps.getProperty('userAgent'): ""));
handler.addCallbackElement(txtAppName);
var lblConsumerKey = app.createLabel('Consumer Key: ');
var txtConsumerKey = app.createTextBox().setName('consumerKey').setWidth("350")
.setValue((scriptProps.getProperty('consumerKey') != null ? scriptProps.getProperty('consumerKey'): ""));
handler.addCallbackElement(txtConsumerKey);
var lblConsumerSecret = app.createLabel('Consumer Secret: ');
var txtConsumerSecret = app.createTextBox().setName('consumerSecret').setWidth("350")
.setValue((scriptProps.getProperty('consumerSecret') != null ? scriptProps.getProperty('consumerSecret'): ""));
handler.addCallbackElement(txtConsumerSecret);
var lblcallBack = app.createLabel('Callback URL:');
var txtcallBack = app.createTextBox().setName('callBack').setWidth("350")
.setValue((scriptProps.getProperty('callbackURL') != null ? scriptProps.getProperty('callbackURL'): ""));
handler.addCallbackElement(txtcallBack);
var lblRSA = app.createLabel('RSA Private Key:');
var txtareaRSA = app.createTextArea().setName('RSA').setWidth("350").setHeight("150")
.setValue((scriptProps.getProperty('rsaKey') != null ? scriptProps.getProperty('rsaKey'): ""));
if (scriptProps.getProperty('appType') == "Private" || scriptProps.getProperty('appType') == null)
txtcallBack.setEnabled(false);
else if (scriptProps.getProperty('appType') == "Public")
txtareaRSA.setEnabled(false);
handler.addCallbackElement(txtareaRSA);
clientHandler1.validateMatches(listAppType, 'Private').forTargets(txtcallBack).setEnabled(false).forTargets(txtareaRSA).setEnabled(true);
clientHandler2.validateMatches(listAppType, 'Public').forTargets(txtcallBack).setEnabled(true).forTargets(txtareaRSA).setEnabled(false);
clientHandler3.validateMatches(listAppType, 'Partner').forTargets(txtcallBack).setEnabled(true).forTargets(txtareaRSA).setEnabled(true);
grid.setBorderWidth(0);
grid.setWidget(0, 0, lblAppType);
grid.setWidget(0, 1, listAppType);
grid.setWidget(1, 0, lblAppName);
grid.setWidget(1, 1, txtAppName);
grid.setWidget(2, 0, lblConsumerKey);
grid.setWidget(2, 1, txtConsumerKey);
grid.setWidget(3, 0, lblConsumerSecret);
grid.setWidget(3, 1, txtConsumerSecret);
grid.setWidget(4, 0, lblcallBack);
grid.setWidget(4, 1, txtcallBack);
grid.setWidget(5, 0, lblRSA);
grid.setWidget(5, 1, txtareaRSA);
grid.setWidget(6, 1, btnSave);
panel1.add(grid).setStyleAttributes(subPanelCSS);
app.add(label1);
app.add(panel1);
ss.show(app);
}
Description
Unfortunately there is no converter. Your dialog is relatively simple and I think I have captured everything of interest. I expect you to handle the property services.
In the dialog I changed the appType from Public to Private to show that the changed values are sent to the server for property service as shown in the execution log.
I inadvertently put include in Code.gs because I normally put CSS in one file, HTML another and js in a third. I didn't do that in this instance.
HTML_Test
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
#label1 { font-weight: bold; }
.textBox { width: 350px; }
.table { display: table; }
.table-row { display: table-row; }
.table-cell { display: table-cell; }
</style>
</head>
<body>
<p id="label1">XERO Settings</p>
<div class="panel1">
<div class="table">
<div class="table-row">
<div class="table-cell">Application Type:</div>
<div class="table-cell">
<select class="textBox" id="appType" onchange="appTypeOnChange()">
<option>Private</option>
<option>Public</option>
<option>Partner</option>
</select>
</div>
</div>
<div class="table-row">
<div class="table-cell">Application Name:</div>
<div class="table-cell">
<input class="textBox" id="userAgent" value=<?= userAgent?>>
</div>
</div>
<div class="table-row">
<div class="table-cell">Consumer Key:</div>
<div class="table-cell">
<input class="textBox" id="consumerKey" value=<?= consumerKey ?>>
</div>
</div>
<div class="table-row">
<div class="table-cell">Consumer Secret:</div>
<div class="table-cell">
<input class="textBox" id="consumerSecret" value=<?= consumerSecret ?>>
</div>
</div>
<div class="table-row">
<div class="table-cell">Callback URL:</div>
<div class="table-cell">
<input class="textBox" id="callBack" value=<?= callBack ?>>
</div>
</div>
<div class="table-row">
<div class="table-cell">RSA Private Key:</div>
<div class="table-cell">
<input class="textBox" id="rsaKey" value=<?= rsaKey ?>>
</div>
</div>
</div>
</div>
<input class="btnSave" type="button" value="Save Settings" onclick="saveSettings()">
<script>
function appTypeOnChange() {
let value = document.getElementById("appType").value;
if( value == "Private" ) {
document.getElementById("callBack").disabled = true;
document.getElementById("rsaKey").disabled = false;
}
else if( appType == "Public" ) {
document.getElementById("callBack").disabled = false;
document.getElementById("rsaKey").disabled = true;
}
else {
document.getElementById("callBack").disabled = false;
document.getElementById("rsaKey").disabled = false;
}
}
function saveSettings() {
let props = {};
props.appType = document.getElementById("appType").value;
props.userAgent = document.getElementById("userAgent").value;
props.consumerKey = document.getElementById("consumerKey").value;
props.consumerSecret = document.getElementById("consumerSecret").value;
props.callBack = document.getElementById("callBack").value;
props.rsaKey = document.getElementById("rsaKey").value;
props = JSON.stringify(props);
google.script.run.setProperties(props);
}
(function () {
let appType = <?= appType ?>;
document.getElementById("appType").value=appType;
if( appType == "Private" ) {
document.getElementById("callBack").disabled = true;
}
else if( appType == "Public" ) {
document.getElementById("rsaKey").disabled = true;
}
}());
</script>
</body>
</html>
Dialog
Code.gs
function showTest() {
try {
let html = HtmlService.createTemplateFromFile('HTML_Test');
html.appType = "Public";
html.userAgent = "John Smith";
html.consumerKey = "12345678";
html.consumerSecret = "My Secret";
html.callBack = "www.goggle.com";
html.rsaKey = "abcdefg";
html = html.evaluate();
SpreadsheetApp.getUi().showModalDialog(html,"Show Test");
}
catch(err) {
SpreadsheetApp.getUi().alert(err);
}
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
};
function setProperties(props) {
Logger.log(props);
}
Execution log
Head setProperties Unknown May 11, 2022, 8:27:15 AM 0.57 s
Completed
Cloud logs
May 11, 2022, 8:27:16 AM Info {"appType":"Private","userAgent":"John Smith","consumerKey":"12345678","consumerSecret":"My Secret","callBack":"www.goggle.com","rsaKey":"abcdefg"}
Reference
HTML Service Templated HTML
I am making a bulletin board system using CKEditor. Most of the features work just fine, but when editing an existing post, the all line breaks in the text are removed from the code block.
Image of create a post
Image of edit a post
Image of part of the response source
I googled as much as possible to solve this problem, but the methods I found were to no avail, so I removed it from the code again.
It seems that line breaks are removed while processing the source internally in CKEditor5, is there any way?
Replace all line breaks with <br /> tags.
Add /\r|\n/g to protectedSource
The following is the view file for that feature.
#model BBSArticleWriteView
#{
// Action name of the current view
var thisActionString = #ViewContext.RouteData.Values["action"].ToString();
if (Model.ArticleId == null)
ViewData["Title"] = "Writing";
else
ViewData["Title"] = "Editing";
}
<p class="page-header">#ViewData["Title"]</p>
<form asp-action="#thisActionString" id="editor-form">
<input asp-for="ArticleId" value="#Model.ArticleId" hidden />
<div>
<input asp-for="Title" required placeholder="Please enter a title." class="form-control w-100 mb-2" />
</div>
<div>
<textarea name="Contents" id="editor">
#Html.Raw(Model.Contents)
</textarea>
</div>
<div>
<input class="btn btn-sm btn-primary" type="submit" value="Save" onsubmit="Editor.submit()" />
<button class="btn btn-sm btn-primary" type="button" href="##" onclick="history.back()">Back</button>
</div>
</form>
<style>
.ck-editor__editable_inline {
min-height: 400px;
}
</style>
#section Scripts {
<script src="~/lib/ckeditor5/ckeditor.js" asp-append-version="true"></script>
<script>
class Editor{
static submit() {
return true;
}
}
ClassicEditor
.create(document.querySelector('#editor'),
{
simpleUpload:{
uploadUrl: "#Url.Action(nameof(CreatorFront.Controllers.FileController.Upload), "File")",
withCredentials: true
},
protectedSource:[
/\r|\n/g
]
})
.catch(error => {
console.error(error);
});
</script>
}
And here is the controller action that puts data into the view model.
[HttpGet]
public async Task<IActionResult> BBSEdit(int id)
{
var user = await _userManager.GetUserAsync(HttpContext.User);
if(user == null)
{
return RedirectToAction("Index", "Home");
}
var article = _cContext.BBSArticle.First(a => a.ArticleId == id);
if(article == null)
{
return RedirectToAction(nameof(BBSList));
}
if(user.Id != article.UserId)
{
return RedirectToAction(nameof(BBSList));
}
var model = new BBSArticleWriteView();
CopyProperties(model, article);
return View(nameof(BBSWrite), model);
}
The following is a function that puts content data in DB.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> BBSWrite(BBSArticleWriteView article)
{
if(ModelState.IsValid)
{
var user = await _userManager.GetUserAsync(HttpContext.User);
if(user == null)
{
RedirectToAction("Index", "Home");
}
// XSS attacks prevent
article.Contents = _htmlSanitizer.Sanitize(article.Contents);
var currentDateTime = DateTime.Now;
CreatorLib.Models.BBS.BBSArticle data = new CreatorLib.Models.BBS.BBSArticle()
{
ArticleId = _cContext.BBSArticle.Max(a => a.ArticleId) + 1,
MainCategory = article.MainCategory,
SubCategory = article.SubCategory,
UserId = user.Id,
Title = article.Title,
Contents = article.Contents,
Status = CreatorLib.Models.BBS.ArticleStatus.A,
IpAddress = HttpContext.Connection.RemoteIpAddress.ToString(),
RegisteredTime = currentDateTime,
LastUpdatedTime = currentDateTime,
HasMedia = article.HasMedia
};
_cContext.BBSArticle.Add(data);
await _cContext.SaveChangesAsync();
return RedirectToAction(nameof(BBSList));
}
return View(article);
}
Here, it is confirmed that HtmlSanitizer has absolutely no impact on this issue.
In DB, line breaks are fully preserved.
How do i save a image in folder in mvc 4.
Here is the code:
<form method="post" class="form-horizontal" name="NewLabelform" enctype="multipart/form-data">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add New Ticket</h4>
</div>
<div class="modal-body">
<p>
<span>Type:</span>
<select class="form-control" id="addtype">
<option value="1">Technical Issue</option>
<option value="2">Bug</option>
<option value="3">Feature Request</option>
<option value="4">Sales Question</option>
<option value="5">How To</option>
</select>
<span id="errortype" style="color: Red;"></span>
</p>
<p>
<span>Title:</span>
<input type="text" class="form-control" id="addTitle" />
<span id="errorTitle" style="color: Red;"></span>
</p>
<p>
<span>description:</span>
<textarea rows="4" cols="50" class="form-control" id="addDesc"></textarea>
<span id="errorDesc" style="color: Red;"></span>
</p>
<p>
<span>Importancy:</span>
<select class="form-control" id="addimportancy">
<option value="1">High</option>
<option value="2">Medium</option>
<option value="3">Low</option>
</select>
<span id="errorimportancy" style="color: Red;"></span>
</p>
<p>
<span>Attached Documents:</span>
<input type="file" name="fileuploader" class="form-control" id="fileuploader" />
<span id="errorAttach" style="color: Red;"></span>
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="CreateLabeData()">Create</button>
</div>
</form>
Here is the Ajax Method:
<script>
var $al = jQuery.noConflict();
function CreateLabeData() {
debugger
var errortype = document.getElementById('errortype');
var addtype = document.getElementById('addtype');
if (addtype.length == "0") {
errortype.innerHTML = "Type is required.";
addtype.focus();
return false;
}
else {
errortype.innerHTML = "";
}
var errorTitle = document.getElementById('errorTitle');
var addTitle = document.getElementById('addTitle');
if (addTitle.value == '') {
errorTitle.innerHTML = "Title is required.";
addTitle.focus();
return false;
}
else {
errorTitle.innerHTML = "";
}
var errorDesc = document.getElementById('errorDesc');
var addDesc = document.getElementById('addDesc');
if (addDesc.value == '') {
errorDesc.innerHTML = "Description is required.";
addDesc.focus();
return false;
}
else {
errorDesc.innerHTML = "";
}
var errorimportancy = document.getElementById('errorimportancy');
var addimportancy = document.getElementById('addimportancy');
if (addimportancy.length == "0") {
errorimportancy.innerHTML = "Importancy is required.";
addimportancy.focus();
return false;
}
else {
errorimportancy.innerHTML = "";
}
//var foldername = document.getElementById("fname").value;
var readdtype = document.getElementById('addtype').value;
var readdTitle = document.getElementById('addTitle').value;
var readdDesc = document.getElementById('addDesc').value;
var readdimportancy = document.getElementById('addimportancy').value;
//var fname = document.querySelector('input[type=file]').files[0].name;
//var doc = $al("#fileuploader").val();
//var filename = doc.replace(/^.*[\\\/]/, '');
//var formData = new FormData();
//var totalFiles = document.getElementById("fileuploader").files.length;
//for (var i = 0; i < totalFiles; i++) {
// var file = document.getElementById("fileuploader").files[i];
// formData.append("fileuploader", file);
//}
//formData.append("fileuploader", file);
$.ajax(
{
//url: "/Ticket/InsertTicket/",
url: '#Url.Content("~/TicketTemplate/InsertTicket")',
type: "POST",
cache: false,
async: true,
datatype: "json",
contentType: 'application/json; charset=utf-8',
//data: JSON.stringify({ 'Addtype': readdtype, 'AddTitle': readdTitle, 'AddDesc': readdDesc, 'Addimportancy': readdimportancy, 'FileName': filename,' FormData': formData }),
data: JSON.stringify({ 'Addtype': readdtype, 'AddTitle': readdTitle, 'AddDesc': readdDesc, 'Addimportancy': readdimportancy }),
success: function (result) {
debugger;
if (result.isSuccess) {
window.location.reload(true);
}
else {
alert('!');
}
},
error: function (result) {
debugger;
alert('');
}
});
}
Here is the controller:
public ActionResult InsertTicket(HttpPostedFileBase FileName, string Addtype, string AddTitle, string AddDesc, string Addimportancy, string FormData)
//public ActionResult InsertTicket( string Addtype, string AddTitle, string AddDesc, string Addimportancy)
{
string isSuccess = "0";
AppTicket models;
AppTicket model = new AppTicket();
model.Type = Convert.ToInt32(Addtype);
model.Title = Convert.ToString(AddTitle);
model.Description = Convert.ToString(AddDesc);
model.Importancy = Convert.ToInt32(Addimportancy);
//obj.Title = Convert.ToString(AddTitle);
int CompanyId = 1;
int status = 1;
//if (FileName != null)
//{
// string saveto = string.Empty;
// // var File = FileName;
// //saveto = Path.Combine(Server.MapPath("~/Content/Areas/Ticket/Content"), FileName);
// // File.SaveAs(saveto);
//}
//var file = Request.Files;
////string saveto = string.Empty;
//string name = string.Empty;
//if (Request.Files.Count > 0)
//{
// var File = Request.Files[0];
// Random rnd = new Random();
// name = rnd.Next(111, 9999).ToString() + "_" + System.IO.Path.GetFileName(File.FileName);
// saveto = Path.Combine(Server.MapPath("~/Content/Areas/Ticket/Content"), name);
// File.SaveAs(saveto);
// // Session["File"] = name;
// Session["File"] = saveto;
//}
Int64? res = _apiTicket.Posts(model.Title, (model.Type), model.Description, (model.Importancy), "", (UserId), CompanyId, false, status);
if (res > 0)
{
isSuccess = "1";
}
return Json(isSuccess, JsonRequestBehavior.AllowGet);
}
How do i save uploaded file in folder??
I have tried a lot but this is not working for me...any suggestion??
In a model popup i need to show the form having all these component.
When click on save it need to save on the folder and name in db.
But it is not working??
So any one can try or give me some solutions??
I have a page that has a dropdownlist and a webgrid. The webgrid has pagenumbers. If I am on page 1 and I select page 2 the item
selected on the dropdown is lost and goes back to "Select Branch"
I want to be able to keep the item selected as I move from page to page. How do I do that? I tried the request.form but did not work
public ActionResult Index()
{
var currentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
Edmviewmodel objedmtest = new Edmviewmodel();
string ddlState_SelectedStateValue = Request.Form["ddlDropDownList"];
if (currentUser != null)
{
try
{
objedmtest = _edmDataService.GetRequiredData("A05");
ViewData["SelectList"] = HttpContext.Session["SelectList"] ?? new List<string>();
}
catch (Exception ex)
{
//logger.Error(ex);
}
}
return View(objedmtest);
}
Here is the html code.
#{
var grid = new WebGrid(source: Model.GetCatDataByLocation,
defaultSort: "CustomerName",
canSort: true,
rowsPerPage: 5
);
}
<div>
<div>
<label for="ddlBranch">Branch:</label>
#Html.DropDownList("ddlDropDownList", Model.BranchesSelectList, "Select Branch", new { #class = "css-class" })
</div>
<div>
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Select", format: #<text><input name="CustomerName" type="checkbox" value="#item.CustomerName" #Html.Raw(((List<string>)ViewData["SelectList"]).Contains(#item.CustomerName) ? "checked" : "") /></text>),
grid.Column("CustomerName", "CustomerName"),
grid.Column("CustomerNumber", "CustomerNumber"),
grid.Column("Orderdate", "Orderdate", canSort: false),
grid.Column("OrderNumber", "OrderNumber"),
grid.Column("Routenumber", "Routenumber"),
grid.Column("Primaryrep", "Primaryrep"),
grid.Column("Isvalidated", "Isvalidated")
)
)
</div>
<div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
//check for existance of query string
var urlg = window.location.href; //global url
var previousIndex = 0;
if (urlg.indexOf("ap") > 0) {
previousIndex = (urlg.substring(urlg.indexOf("ap=") + 3));
}
$('select>option:eq(' + previousIndex + ')').prop('selected', true); //zero-based
$("a").click(function (event) {
$("td a").each(function () {
var old = $(this).attr('href');
idx = $("select[name='ddlDropDownList'] option:selected").index();
$(this).attr("href", old + "&ap=" + idx);
});
});
});
</script>
My application layout has a partial that is a form with a textbox and a dropdown. Based on the criteria entered/selected, the form post performs a RedirectToRoute in a base controller. However, the page load time is excessively high and seems to be hung up on the redirect. A competitor site's redirect (using what appears to be PHP) is lightning fast. What could be causing the slowness in the RedirectToRoute and is there an alternate method that should be used here to evaluate where the process should flow upon form post?
<div class="search_widget">
<h2> </h2>
<div class="property-filter-header">
<div class="content">
#*<h4>FIND SENIOR HOUSING<br />AND CARE</h4>*#
<h4>FIND SENIOR HOUSING AND CARE</h4>
</div>
</div>
<div class="property-filter">
<div class="content">
#using (Html.BeginForm("SearchCare", "Base", FormMethod.Post, new { id = "searchForm" }))
{
<div class="location control-group">
<label class="control-label" for="Location">
Enter/select location
</label>
<div class="controls">
#Html.TextBoxFor(model => model.Location, new { #class = "location", placeholder = "City and State", required = "required" })
</div><!-- /.controls -->
</div><!-- /.control-group -->
<div class="type control-group">
<label class="control-label" for="Level">
Select an option
</label>
<div class="controls">
#Html.DropDownListFor(model => model.Level, AFS.HelperClasses.Lookups.LevelOfCare.LevelOfCareSelectList, " ", new { required = "required" })
</div><!-- /.controls -->
</div><!-- /.control-group -->
<div class="form-actions">
<input type="submit" value="Search!" class="btn btn-primary btn-large">
</div><!-- /.form-actions -->
<div style="text-align: center; margin-top: 10px;">
<img src="#Url.Content("~/assets/img/sunburst-yellow.png")" alt="AFS sunburst" />
</div>
#Html.Hidden("city");
#Html.Hidden("state");
#Html.Hidden("lat");
#Html.Hidden("lng");
}
</div><!-- /.content -->
</div><!-- /.property-filter -->
Here is the post action:
[HttpPost]
public ActionResult SearchCare(SearchModel model, FormCollection form)
{
if (ModelState.IsValid)
{
string state = form["state"].ToString();
string city = form["city"].ToString();
string lat = form["lat"].ToString();
string lng = form["lng"].ToString();
if (string.IsNullOrEmpty(state) || string.IsNullOrEmpty(city))
{
string[] location = model.Location.Split(',');
city = location[0].Replace(" ", "-");
if (location.Length > 1)
{
state = location[1].Trim();
}
else
{
return RedirectToAction("Location", "Errors", new { location = model.Location });
}
}
string controller = "";
switch (model.Level)
{
case 1:
controller = "AdultDayCare";
return RedirectToRoute("AdultDayCareByLocation", new { State = state, City = city });
case 2:
controller = "AlzheimersSpecialty";
return RedirectToRoute("AlzheimersSpecialtyByLocation", new { State = state, City = city });
case 3:
controller = "AssistedLiving";
return RedirectToRoute("AssistedLivingByLocation", new { State = state, City = city});
//return RedirectToRoute("AssistedLivingByLocation", new { State = state, City = city, latitude = lat, longitude = lng });
case 4:
controller = "ContinuingCare";
return RedirectToRoute("ContinuingCareByLocation", new { State = state, City = city });
case 5:
controller = "HomeCare";
return RedirectToRoute("HomeCareByLocation", new { State = state, City = city });
case 6:
controller = "Hospice";
return RedirectToRoute("HospiceByLocation", new { State = state, City = city });
case 7:
controller = "IndependentLiving";
return RedirectToRoute("IndependentLivingByLocation", new { State = state, City = city });
case 8:
controller = "Nursing";
return RedirectToRoute("NursingByLocation", new { State = state, City = city });
case 9:
controller = "ResidentialCare";
return RedirectToRoute("ResidentialCareByLocation", new { State = state, City = city });
case 10:
controller = "SeniorApartments";
return RedirectToRoute("SeniorApartmentsByLocation", new { State = state, City = city });
};
return RedirectToAction("Results", controller, new { State = state, City = city });
}
else
{
return RedirectToAction("SearchError");
}
}
Thanks in advance!!