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??
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
this is my form I am using mvc in VS2013 where I am little confused about whats happening here, it is returning me empty fields while I am passing required data, although it is ok when fields are empty but when it has data in it it should be fired a successfully sent it but it is not working
guys please help me to get my this code working
View
#using (Html.BeginForm("RegUser", "User", FormMethod.Post, new { #id = "myForm" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="form-horizontal custom_frmHorizontal">
<fieldset>
<!-- Form Name -->
<!-- Text input-->
<div class="form-group">
<div class="col-md-12">
#*#Html.HiddenFor(model => model.Subscription)*#
#Html.TextBoxFor(model => model.CompanyName, new { #class = "form-control input-md", #autocomplete = "off", #placeholder = "Company Name", #id = "txtName" })
#Html.ValidationMessageFor(model => model.CompanyName, null, new { #class = "text-danger" })
<span id="ern" class="field-validation-error text-danger" data-valmsg-for="CompanyName" data-valmsg-replace="true" style="display:none;"></span>
</div>
</div>
<div class="form-group">
#*<label class="col-md-4 control-label" for="textinput">Email Address :</label>*#
<div class="col-md-12">
#*<input id="textinput" name="textinput" type="text" placeholder="Email Address" class="form-control input-md">*#
#Html.TextBoxFor(model => model.Email, new { #class = "form-control input-md", #style = "background-color:transparent !important;", #autocomplete = "off", #placeholder = "Email Address", #id = "txtemail" })
#Html.ValidationMessageFor(model => model.Email, null, new { #class = "text-danger" })
<span id="ere" class=" field-validation-error text-danger" data-valmsg-for="Email" data-valmsg-replace="true" style="display:none;"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(model => model.Mobile, new { #class = "form-control input-md", #autocomplete = "off", #placeholder = "Phone Number", #id = "txtMobile" })
#Html.ValidationMessageFor(model => model.Mobile, null, new { #class = "text-danger" })
<span id="ermob" class=" field-validation-error text-danger" style="display:none;"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(model => model.CRN, new { #class = "form-control input-md", #autocomplete = "off", #placeholder = "Company CRN", #id = "txtCrn" })
#Html.ValidationMessageFor(model => model.CRN, null, new { #class = "text-danger" })
<span id="ercrn" class=" field-validation-error text-danger" style="display:none;"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(model => model.EmpStrength, new { #class = "form-control", #autocomplete = "off", #placeholder = "Employees Strength", #id = "txtEmpStr" })
#Html.ValidationMessageFor(model => model.EmpStrength, null, new { #class = "text-danger" })
<span id="eremp" class="field-validation-error text-danger" style="display:none;"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(model => model.Address, new { #class = "form-control input-md", #autocomplete = "off", #placeholder = "Company Address", #id = "txtCadrs" })
#Html.ValidationMessageFor(model => model.Address, null, new { #class = "text-danger" })
<span id="eradrs" class="errmsg field-validation-error text-danger" style="display:none;"></span>
</div>
</div>
<div class="form-group btn_wrap">
<div class="col-md-12">
<button id="formSubmit" value="Submit" type="submit" class="btnCutom1 btn btn-primary">Send Request<i class="far fa-paper-plane pl-3"></i></button>
</div>
</div>
</fieldset>
</div>
}
Jquery
$('#myForm').on('submit', function(event) {
var frmData = $("myForm");
event.preventDefault()
var name = document.getElementById('txtName').value;
var email = document.getElementById('txtemail').value;
var mobile = document.getElementById('txtMobile').value;
var crn = document.getElementById('txtCrn').value;
var emp = document.getElementById('txtEmpStr').value;
var adrs = document.getElementById('txtCadrs').value;
if (name.length == 0) {
//alert("Please insert Company Name");
$("#ern").text("Company name must required").fadeIn();
}
if (email.length == 0) {
$("#ere").text("Please insert email address").fadeIn();
}
if (mobile.length == 0) {
//alert("Please insert Mobile Number");
$("#ermob").text("Please insert Mobile Number").fadeIn();
}
if (crn.length == 0) {
//alert("Please insert CRN");
$("#ercrn").text("Please insert CRN").fadeIn();
}
if (emp.length == 0) {
//alert("Please insert Employees");
$("#eremp").text("Please insert Employees Strength").fadeIn();
}
if (adrs.length == 0) {
//alert("Please insert Address");
$("#eradrs").text("Please insert Company Address").fadeIn();
} else {
//var frmData = $("myForm");
//e.preventDefault();
$.ajax({
type: "Post",
ContentType: "application/json; charset=utf-8",
data: "{frmData:" + JSON.stringify(frmData) + "}",
// url: "pricing/Index",
success: function(data) {
alert("sent successfully:" + data);
location.window.href = "RegUser/User";
},
error: function(result) {
//$form = $(this);
alert("something went wrong");
}
});
}
});
Controller
public class UserController : Controller
{
//
// GET: /User/
[HttpGet]
public ActionResult RegUser(int id=0)
{
UserDtl userModel = new UserDtl();
return View(userModel);
}
[HttpPost]
public ActionResult RegUser(UserDtl userModel, string CompanyName, string Email, string CRN, string EmpStrength, string Mobile, string Address)
{
try
{
using (DbModels dbModel = new DbModels())
{
dbModel.UserDtls.Add(userModel);
dbModel.SaveChanges();
}
if (ModelState.IsValid)
{
var senderemail = new MailAddress("shakil.7878#gmail.com", "deem-admin");
var receiveremail = new MailAddress(Email, "New Request");
var password = "inDia123#";
var sub = CompanyName;
string bodyText = string.Format("<table border='0' cellpadding='0' cellspacing='0' style='width:600px; background:#efefef;'> <tr><td colspan='2'><center><img src='https://drcoder1tcircle.000webhostapp.com/mh.jpg' /></center></td></tr><tr><td colspan='2'><center><img src='https://drcoder1tcircle.000webhostapp.com/ms.jpg' /></center></td></tr> <tr><td style='height:40px;'></td> <td style='height:40px;'></td></tr> <tr> <td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'><b>New Request</b></td><td> </td></tr> <tr><td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'>Company Name: </td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{0}</td> </tr> <tr><td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'>Email Address: </td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{1}</td> </tr> <tr> <td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'> Company Registration No.</td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{2}</td> </tr> <tr> <td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'>Employees Strength</td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{3}</td></tr> <tr><td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'> Mobile No.</td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{4}</td></tr> <tr><td style='color:#000000;text-align:right; font-family:Arial; font-size:12px;'> Company Address</td> <td style='color:#000000;text-align:center; font-family:Arial; font-size:12px;'>{5}</td> </tr> <tr><td style='height:40px;'></td> <td style='height:40px;'></td></tr> <tr><td style='background:#303030; height:30px;' colspan='2'><center><a style='color:#ffffff; text-align:center; font-family:Arial; font-size:12px;' href='#' target='_blank'>www.deem.sa</a></center></td></tr> </table>", CompanyName, Email, CRN, EmpStrength, Mobile, Address);
var body = bodyText;
var smtp = new SmtpClient
{Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(senderemail.Address, password)};
var mess = new MailMessage(senderemail, receiveremail)
{Subject = sub,
Body = body,
IsBodyHtml = true};
smtp.Send(mess);
ModelState.Clear();
ViewBag.SuccessMessage = "Request sent Successful. We will send you Registration Details on your email address.";
return View();
}
//ModelState.Clear();
//ViewBag.SuccessMessage = "Request sent Successful. We will send you Registration Details on your email address.";
}
catch (Exception ex)
{
}
return View("RegUser", new UserDtl());
}
}
You can't specify the DOM id for your input elements like this (#id = "txtName"). The id is automatically generated by the framework. If you view the source in your browser, you will see these elements have been rendered with 2 ids. This is invalid HTML, causing your breakage.
There are accepted answers to other questions here on SO basically saying you can capitalize #id to fix this (i.e. #Id), but the users providing these answers don't understand how the attributes on these elements are generated, and are simply observing a side effect of a hack that is not actually guaranteed to work in any scenario, though it may happen to work in a few browsers under certain conditions right now.
Instead, remove any use of "#id=", and use the #Html.IdFor() helper to determine the assigned ID. For example:
<script>
var myId = "#Html.IdFor(m => m.CompanyName)";
</script>
You would then use this Javascript variable (e.g. myId) in place of the ID you invented ("txtName") in the rest of your code .. for example, you'd change this:
var name = document.getElementById('txtName').value;
To this:
var name = document.getElementById(myId).value;
And since you're using jQuery, you may alternatively express this as follows:
var name = $("#" + myId).val();
Then the generated HTML will be valid and your form will post as expected.
$('#myForm').on('submit', function (event) {
var frmData = $("myForm");
// event.preventDefault()
var myCn = "#Html.IdFor(m => m.CompanyName)";
var myEm = "#Html.IdFor(m => m.Email)";
var myMo = "#Html.IdFor(m => m.Mobile)";
var myCr = "#Html.IdFor(m => m.CRN)";
var myEp = "#Html.IdFor(m => m.EmpStrength)";
var myAd = "#Html.IdFor(m => m.Address)";
var name = document.getElementById(myCn).value;
var email = document.getElementById(myEm).value;
var mobile = document.getElementById(myMo).value;
var crn = document.getElementById(myCr).value;
var emp = document.getElementById(myEp).value;
var adrs = document.getElementById(myAd).value;
//var name = $("#" + myCn).val();
//var email = $("#" + myEm).val();
//var mobile = $("#" + myMo).val();
//var crn = $("#" + myCr).val();
//var emp = $("#" + myEp).val();
//var adrs = $("#" + myAd).val();
if (name.length == 0) {
//alert("Please insert Company Name");
$("#ern").text("Company name must required").fadeIn();
} if (email.length == 0) {
$("#ere").text("Please insert email address").fadeIn();
} if (mobile.length == 0) {
//alert("Please insert Mobile Number");
$("#ermob").text("Please insert Mobile Number").fadeIn();
}
if (crn.length == 0) {
//alert("Please insert CRN");
$("#ercrn").text("Please insert CRN").fadeIn();
}
if (emp.length == 0) {
//alert("Please insert Employees");
$("#eremp").text("Please insert Employees Strength").fadeIn();
}
if (adrs.length == 0) {
//alert("Please insert Address");
$("#eradrs").text("Please insert Company Address").fadeIn();
}
else {
//var frmData = $("myForm");
//e.preventDefault();
$.ajax({
type: "Post",
ContentType: "application/json; charset=utf-8",
data: "{frmData:" + JSON.stringify(frmData) + "}",
// url: "pricing/Index",
success: function (data) {
alert("sent successfully:" + data);
location.window.href = "RegUser/User";
},
error: function (result) {
//$form = $(this);
alert("something went wrong");
}
});
}
});
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
HTML code:
<div class="col-sm-9">
<input name="NewCardOrAccountNumber" class="form-control ui-autocomplete-input" id="NewCardOrAccountNumber" type="text" value="" autocomplete="off">
<span class="ui-helper-hidden-accessible" role="status" aria-live="polite"></span>
</div>
<div class="unvisible" id="clientInfoNew">
<div class="form-group">
<label class="col-sm-3 control-label">FIRST NAME</label>
<div class="col-sm-9" id="FnameNew"></div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">LAST NAME</label>
<div class="col-sm-9" id="LnameNew"></div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">BIRTH DATE</label>
<div class="col-sm-9" id="BirthDateNew"></div>
</div>
Watin code:
[TestMethod]
[TestCategory("Rimi Change card page")]
public void Rimi_4444_Change_Card_and_Assert()
{
//Web Address
using (IE ie = new IE(this.Rimi))
{
//IE ie = new IE(RimiChangeCard);
ie.BringToFront();
ie.ShowWindow(WatiN.Core.Native.Windows.NativeMethods.WindowShowStyle.Maximize);
ie.TextField(Find.ById("NewCardOrAccountNumber")).TypeText("9440385200600000020");
If I write card number from keyboard, the invisible class appear, and you can see FIRST NAME, LAST NAME and so on. But if I do this with watin, it does not appear, and you only see card number which you input. Its like hidden fields of information. I do not know how to make that I could see this fields when I input card number.
There would be a JavaScript function, which gets executed when you manually enter the data in the text field.Go through the Java Script functions on the same page which refer to that element using it's ID NewCardOrAccountNumber.
Refer to this link for sample application. Where msg_to is element, and has a KeyUp event associated. When that filed gets a , value, there is a div section inside which a `Subject' field is shown.
Similarly, after executing the TypeText, try to trigger related event mentioned in the Java Script event using Java script execution.
EDIT: I see that the javascript functions gets executed after bulr event is fired. This means the textbox field should loose the focus. Try the below options.
// 1. Try focusing out of control.
ie.TextField(Find.ById("NewCardOrAccountNumber")).TypeText("9440385200600000020");
ie.TextField(Find.ById("OldCardOrAccountNumber")).Click();
ie.WaitForComplete();
// 2. Try Using Send Keys method to tab out.
ie.TextField(Find.ById("NewCardOrAccountNumber")).TypeText("9440385200600000020");
System.Windows.Forms.SendKeys.SnedWait("{TAB}"); // Need to add System.Windows.Forms reference to the project.
I put image on the internet, so click on this link Image and you will see on first image how look page, second picture - what have to happen when you input card number (from keyboard), third - what happen when card namuber is input from watin (does not appear information about card).
HTML code:
<div class="ibox-content">
<br>
<div class="form-horizontal">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<label class="col-sm-3 control-label">NEW CARD</label>
<input name="NewCardId" id="NewCardId" type="hidden" value="0" data-val-required="The NewCardId field is required." data-val-number="The field NewCardId must be a number." data-val="true">
<div class="col-sm-9"><span class="ui-helper-hidden-accessible" role="status" aria-live="polite"></span><input name="NewCardOrAccountNumber" class="form-control ui-autocomplete-input" id="NewCardOrAccountNumber" type="text" value="" autocomplete="off"></div>
</div>
<div class="unvisible" id="clientInfoNew">
<div class="form-group">
<label class="col-sm-3 control-label">FIRST NAME</label>
I maybe find what you looking for Sham, but I do not know how to use it :
<script type="text/javascript">
$(document).ready(function() {
var NewCardId = "#NewCardId";
var OldCardId = "#OldCardId";
var NewCardNumber = "#NewCardOrAccountNumber";
var OldCardNumber = "#OldCardOrAccountNumber";
$(NewCardNumber).autocomplete(
{
source: function(request, response) {
$.ajax({
url: '/LoyaltyWebApplication/Suggestion/GetCardSuggestions',
dataType: "json",
data: {
str: $(NewCardNumber).val()
},
success: function(data) {
response($.map(data, function(item) {
var label = "";
if (item.Fname != null) label += item.Fname;
if (item.Lname != null) label += " " + item.Lname;
if (label.trim() != '') label = " (" + label.trim() + ")";
return {
value: item.CardNumber,
label: item.CardNumber + label
}
}));
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
},
select: function(event, ui) {
getCardDetails($(NewCardNumber), $(NewCardId), 'newCardSegments', true);
$("#newCardSegments").hide();
$("#clientInfoNew").show();
},
minLength: 2
}).blur(function() {
getCardDetails($(NewCardNumber), $(NewCardId), 'newCardSegments', true);
});
$(OldCardNumber).autocomplete(
{
source: function(request, response) {
$.ajax({
url: '/LoyaltyWebApplication/Suggestion/GetCardSuggestions',
dataType: "json",
data: {
str: $(OldCardNumber).val()
},
success: function(data) {
response($.map(data, function(item) {
var label = "";
if (item.Fname != null) label += item.Fname;
if (item.Lname != null) label += " " + item.Lname;
if (label.trim() != '') label = " (" + label.trim() + ")";
return {
value: item.CardNumber,
label: item.CardNumber + label
}
}));
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
},
select: function(event, ui) {
getCardDetails($(OldCardNumber), $(OldCardId), 'oldCardSegments', false);
$("#oldCardSegments").hide();
},
minLength: 2
}).blur(function() {
getCardDetails($(OldCardNumber), $(OldCardId), 'oldCardSegments', false);
});
function getCardDetails(cardNumHolder, cardIdHolder, segmentTablePlace, isNew) {
$.getJSON('/LoyaltyWebApplication/LOV/SetId?lovType=ReplacementLOV&lovValue=' + cardNumHolder.val(), null,
function(data) {
$("#clientInfo" + ((isNew) ? "New" : "Old")).show();
if (cardNumHolder.val() == '') {
return;
}
var i;
for (i = 0; i < data.otherNames.length; i++) {
$("#" + data.otherValues[i] + (isNew ? "New" : "Old")).text(data.otherNames[i]);
}
cardIdHolder.val(data.Id);
$.getJSON('/LoyaltyWebApplication/Replacement/ClientSegmentsList?clientId=' + data.Id + "&no_cache=" + Math.random, function(data) {
$("#" + segmentTablePlace).find('tbody').empty();
if (data.length > 0) {
$.each(data, function(index) {
$("#" + segmentTablePlace).find('tbody').append("<tr><td>" + data[index].SegmentCode + "</td><td>" + data[index].SegmentName + "</td></tr>");
});
$("#" + segmentTablePlace).show();
}
});
});
}
$("#resetVal").click(function() {
$("#NewCardOrAccountNumber").attr("value", "");
$("#NewCardOrAccountNumber").val("");
$("#NewCardId").attr("value", "");
$("#NewCardId").val("");
$("#clientInfoNew").hide();
$("#OldCardOrAccountNumber").attr("value", "");
$("#OldCardOrAccountNumber").val("");
$("#OldCardId").attr("value", "");
$("#OldCardId").val("");
$("#clientInfoOld").hide();
return false;
});
});
</script>
I have a single page with multiple partials set up. I want to be able to validate and update each partial seperatly. The validation works BUT when I type in a correct value and press save the page goes to the partial view instead of staying on the single page. What am I doing wrong here?
This is my main page :
#for (var i = 0; i < 10; i++)
{
var idTest = "Test_" + i;
<div id="#idTest">
#Html.Action("Detail", new { id = i })
</div>
}
The partial is created like this:
#{
var idTest = "Test_" + Model.Id;
var ajaxOptions = new AjaxOptions
{
UpdateTargetId = #idTest,
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace
};}
#using (Ajax.BeginForm("Detail", ajaxOptions))
{ #Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Test</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Gemeente, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Gemeente, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Gemeente, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
This is the simple model:
public class Test
{
public int Id { get; set; }
[Required(ErrorMessage = "Gelieve een gemeente op te geven")]
public string Gemeente { get; set; }
}
These are the actions:
[HttpGet]
public ActionResult Detail(int id)
{
Models.Test model = new Models.Test();
model.Id = id;
return View(model);
}
[HttpPost]
public ActionResult Detail(Models.Test model)
{
if(ModelState.IsValid)
{
return PartialView(model);
}
return PartialView(model);
}
Add these lines to your view and also use #Html.Partial as shown below
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
so that your main view is
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#for (var i = 0; i < 10; i++)
{
var idTest = "Test_" + i;
<div id="#idTest">
#Html.Partial("Detail", new Test { Id = i })}
</div>
}
Scripts would be for unobtrusive ajax so that your ajax button works and Html.Partial so that first time when you load your page in foreach only partial view is rendered (not the full view)