I am quite new to MVC and coding, so apologies if I don't bring it to the point. I am encountering a weird issue that I somehow cannot manage to solve:
I want to submit a form that includes an image along with other values, such as user name, user ID, timestamp, etc. and write it into a table (SQL); now I can get the image as byte to the DB and I can get the form submitted to the DB, but for some reason I cannot get it done at the same time, so it's either the image/file or the form. The error I encounter is the following:
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
View Model:
namespace errandomWeb.Models
{
public class PhotoCompetition
{
public int ID { get; set; }
public string UserID { get; set; }
public string FirstName { get; set; }
public string Email { get; set; }
public byte[] CompetitionPicture { get; set; }
//[Required]
[Display(Name = "by checking this box I accept the Terms & Conditions")]
public bool TermsAndConditionsAccepted { get; set; }
public DateTime TimeStamp { get; set; }
}
}
Controller (getting error message):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadCompetitionPicture(PhotoCompetition model)
{
string croppedImage = Request.Form["photoCompetitionCroppedPicture"];
byte[] imageBytes = Convert.FromBase64String(croppedImage);
var userId = User.Identity.GetUserId();
var participation = new PhotoCompetition
{
CompetitionPicture = imageBytes,
UserID = User.Identity.GetUserId(),
FirstName = "testcase",
Email = User.Identity.GetUserName(),
TermsAndConditionsAccepted = true,
TimeStamp = DateTime.UtcNow.ToUniversalTime(),
};
DB.PhotoCompetition.Add(participation);
DB.SaveChanges();
return View("Edit");
}
}
Controller (working for image, but not the form...):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadCompetitionPicture()
{
string croppedImage = Request.Form["photoCompetitionCroppedPicture"];
byte[] imageBytes = Convert.FromBase64String(croppedImage);
var userId = User.Identity.GetUserId();
var participation = new PhotoCompetition
{
CompetitionPicture = imageBytes,
UserID = User.Identity.GetUserId(),
FirstName = "testcase",
Email = User.Identity.GetUserName(),
TermsAndConditionsAccepted = true,
TimeStamp = DateTime.UtcNow.ToUniversalTime(),
};
DB.PhotoCompetition.Add(participation);
DB.SaveChanges();
return View("Edit");
}
}
View:
#model errandomWeb.Models.PhotoCompetition
#{
ViewBag.Title = "Become Our Model";
}
<div id="photoCompetitionContainer" class="manageContainer">
<div id="photoCompetitionHeaderSection" class="manageHeaderSection">
<h1 id="photoCompetitionHeaderTitle" class="manageHeaderTitle">
#ViewBag.Title
</h1>
<img id="photoCompetitionHeaderProfilePicture" class="manageHeaderProfilePicture" src="#Url.Action("UserPicture", "Manage")" />
<p id="photoCompetitionHeaderPersonalizationGeneric" class="manageHeaderPersonalization">
Hello
</p>
<p id="photoCompetitionHeaderPersonalizationName" class="manageHeaderPersonalization">
#Html.TextBoxFor(m => m.FirstName, new { #id = "photoCompetitionHeaderUserName", #class = "manageHeaderUserName", #placeholder = "Stranger", #disabled = true })
</p>
</div>
#Html.Partial("_ProfileLogout")
<div id="photoCompetitionContextSection" class="manageContextSection">
<p id="photoCompetitionContext" class="manageContext">
Want to become our model?
</p>
</div>
<div id="photoCompetitionValidationSection" class="manageValidation">
#Html.ValidationSummary("", new { #id = "photoCompetitionValidation", #class = "manageValidation" })
</div>
<section id="photoCompetition" class="manageForm">
#using (Html.BeginForm("UploadCompetitionPicture", "errandom", FormMethod.Post, new { #id = "photoCompetitionForm", #class = "form-horizontal", #role = "form", #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div id="photoCompetitionSection" class="manageSection">
<p id="photoCompetitionSectionTitle" class="manageSectionTitle">
Upload your picture and be selected as our model!
</p>
#Html.HiddenFor(m => m.UserID)
#Html.HiddenFor(m => m.Email)
#Html.HiddenFor(m => m.FirstName)
#Html.HiddenFor(m => m.TimeStamp)
<div id="photoCompetitionProfilePictureArea" class="manageArea row">
#Html.LabelFor(m => m.CompetitionPicture, new { #id = "photoCompetitionProfilePictureLabel", #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="photoCompetitionProfilePictureSelectionButton" class="manageField col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset0 col-md-7 col-lg-offset-0 col-lg-6" href="#">
select a file...
</a>
#Html.TextBoxFor(m => m.CompetitionPicture, new { #id = "photoCompetitionProfilePictureField", #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>
<div id="photoCompetitionTermsAndConditionsArea" class="manageArea row">
#Html.CheckBoxFor(m => m.TermsAndConditionsAccepted, new { #id = "photoCompetitionTermsAndConditionsField", #class = "photoCompetitionTermsAndConditionsField" })
#Html.LabelFor(m => m.TermsAndConditionsAccepted, new { #id = "photoCompetitionTermsAndConditionsLabel", #class = "photoCompetitionTermsAndConditionsLabel" })
#Html.ValidationMessageFor(m => m.TermsAndConditionsAccepted, "", new { #id = "photoCompetitionTermsAndConditionsValidation", #class = "manageValidation 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" })
</div>
<script>
jQuery("#photoCompetitionProfilePictureSelectionButton").click(function () {
$("#photoCompetitionProfilePictureField").click();
});
</script>
<script>
$("#photoCompetitionProfilePictureField").change(function () {
var fullFileName = $("#photoCompetitionProfilePictureField").val()
$("#photoCompetitionProfilePictureSelectionButton").html(fullFileName.substr(fullFileName.lastIndexOf('\\') + 1));
});
</script>
<div id="photoCompetitionCroppingArea" class="manageArea row">
<img id="photoCompetitionOriginal" class="photoCompetitionImage" src="" alt="" style="display: none" />
<canvas id="photoCompetitionCropped" class="photoCompetitionImage" height="5" width="5"></canvas>
</div>
<div id="photoCompetitionButtonArea" class="manageArea row">
<input id="photoCompetitionButtonCrop" 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" style="display: none" />
<input id="photoCompetitionButtonUpload" 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="submit" value="Save" style="display: none" />
<input id="photoCompetitionCropX" class="photoCompetitionData" name="photoCompetitionCropX" type="hidden" />
<input id="photoCompetitionCropY" class="photoCompetitionData" name="photoCompetitionCropY" type="hidden" />
<input id="photoCompetitionCropW" class="photoCompetitionData" name="photoCompetitionCropW" type="hidden" />
<input id="photoCompetitionCropH" class="photoCompetitionData" name="photoCompetitionCropH" type="hidden" />
<input id="photoCompetitionCroppedPicture" class="photoCompetitionData" name="photoCompetitionCroppedPicture" type="hidden" />
</div>
</div>
}
</section>
<div id="photoCompetitionReturnToMenuSection" class="manageReturnToMenuSection">
#Html.ActionLink("Return to Menu", "Index", "", htmlAttributes: new { #id = "photoCompetitionReturnToMenuButton", #class = "manageReturnToMenuButton" })
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/tapmodo/Jcrop/master/js/jquery.Jcrop.min.js"></script>
<script type="text/javascript">
$(function () {
if ($('#photoCompetitionCroppingArea').width() > 700) {
$('#photoCompetitionProfilePictureField').change(function () {
$('#photoCompetitionOriginal').hide();
var reader = new FileReader();
reader.onload = function (e) {
$('#photoCompetitionOriginal').show();
$('#photoCompetitionOriginal').attr("src", e.target.result);
$('#photoCompetitionOriginal').Jcrop({
onChange: SetCoordinates,
onSelect: SetCoordinates,
aspectRatio: 1,
boxWidth: 600,
addClass: 'photoCompetitionCropping'
});
}
reader.readAsDataURL($(this)[0].files[0]);
});
}
else {
$('#photoCompetitionProfilePictureField').change(function () {
$('#photoCompetitionOriginal').hide();
var reader = new FileReader();
reader.onload = function (e) {
$('#photoCompetitionOriginal').show();
$('#photoCompetitionOriginal').attr("src", e.target.result);
$('#photoCompetitionOriginal').Jcrop({
onChange: SetCoordinates,
onSelect: SetCoordinates,
aspectRatio: 1,
boxWidth: 250,
addClass: 'photoCompetitionCropping'
});
}
reader.readAsDataURL($(this)[0].files[0]);
});
}
$('#photoCompetitionButtonCrop').click(function () {
var x1 = $('#photoCompetitionCropX').val();
var y1 = $('#photoCompetitionCropY').val();
var height = $('#photoCompetitionCropH').val();
var width = $('#photoCompetitionCropW').val();
var canvas = $("#photoCompetitionCropped")[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,/, "");
$('#photoCompetitionCroppedPicture').val(image);
$('#photoCompetitionButtonUpload').show();
$('#photoCompetitionCropped').hide();
$('#photoCompetitionButtonCrop').hide();
};
img.src = $('#photoCompetitionOriginal').attr("src");
});
});
function SetCoordinates(c) {
$('#photoCompetitionCropX').val(c.x);
$('#photoCompetitionCropY').val(c.y);
$('#photoCompetitionCropW').val(c.w);
$('#photoCompetitionCropH').val(c.h);
$('#photoCompetitionButtonCrop').show();
};
</script>
}
If anyone has an idea on how I could submit the image while also submitting the other properties I would highly appreciate guidance/advice! Thank you!
I finally got it done. Here's the updated controller code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadCompetitionPicture([Bind(Exclude = "CompetitionPicture")]PhotoCompetition model)
{
string croppedImage = Request.Form["photoCompetitionCroppedPicture"];
byte[] imageBytes = Convert.FromBase64String(croppedImage);
var userId = User.Identity.GetUserId();
var participation = new PhotoCompetition
{
UserID = User.Identity.GetUserId(),
FirstName = "Ken",
Email = User.Identity.GetUserName(),
TermsAndConditionsAccepted = true,
TimeStamp = DateTime.UtcNow.ToUniversalTime(),
};
participation.CompetitionPicture = imageBytes;
DB.PhotoCompetition.Add(participation);
DB.SaveChanges();
return View("Edit");
}
I guess, what made the difference is excluding the picture in the first place, then submitting all other fields and after that adding the picture separately. Not sure why, but glad I figured it out.
Related
I have a registration form and there is two inputs for password and password confirmation. When I enter distinct values I wanted it to show the error message as 'Passwords should match' or something. So I googled it and found out that update-package should fix this problem. Then I applied this solution in order to fix my problem, now, neither my error message shows up nor my submit button works.
My Registration View:
<div class="container-fluid">
#using (Html.BeginForm("Register", "User", FormMethod.Post, new { #class = "col-12" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal p-3 m-3 w-100 d-flex flex-column align-items-center">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group w-100">
<label class="form-control-label col-md-12">Kullanıcı adı</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.kullaniciAdi, new { htmlAttributes = new { #class = "form-control", #required = "required" } })
#Html.ValidationMessageFor(model => model.User.kullaniciAdi, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Firma adı</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.firmaAdi, new { htmlAttributes = new { #class = "form-control", #required = "required" } })
#Html.ValidationMessageFor(model => model.User.firmaAdi, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Şifre</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.sifre, new { htmlAttributes = new { #class = "form-control", #required = "required", #type = "password" } })
#Html.ValidationMessageFor(model => model.User.sifre, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Şifre tekrar</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.sifreTekrar, new { htmlAttributes = new { #class = "form-control", #required = "required", #type = "password" } })
#Html.ValidationMessageFor(model => model.User.sifre, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">E-mail</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.mail, new { htmlAttributes = new { #class = "form-control", #required = "required", #type = "text" } })
#Html.ValidationMessageFor(model => model.User.mail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Telefon</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.telefon, new { htmlAttributes = new { #class = "form-control", #type = "text", #required = "required" } })
#Html.ValidationMessageFor(model => model.User.telefon, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Ülkeniz</label>
#Html.EditorFor(model => model.Address.ulkeID, new { htmlAttributes = new { #class = "form-control", #type = "text", #readonly="readonly", #Value="Türkiye" } })
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Bulunduğunuz il</label>
<select class="form-control col-md-12" name="Address.sehirID" id="il" required></select>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Bulunduğunuz ilçe</label>
<select class="form-control col-md-12" name="Address.ilceID" id="ilce" disabled required>
<option>Bir İl Seçiniz</option>
</select>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Açık adresiniz</label>
<div class="col-md-12">
#Html.EditorFor(model => model.Address.acikAdres, new { htmlAttributes = new { #class = "form-control", #type = "text", #required = "required" } })
#Html.ValidationMessageFor(model => model.Address.acikAdres, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Oluşturulma Tarihi</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.olusturulmaTarihi, new { htmlAttributes = new { #class = "form-control", #type = "text", #readonly="readonly", #Value=sqlFormat } })
#Html.ValidationMessageFor(model => model.Address.acikAdres, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<div class="col-md-offset-2 col-md-12">
<input type="submit" value="Kaydol" class="btn btn-success" />
</div>
</div>
</div>
}
</div>
Register Action:
[HttpPost]
public ActionResult Register(RegisterVM model)
{
tblKullanici user = null;
tblAdres address = null;
if(model != null)
{
db = new DatabaseContext();
user = model.User;
address = model.Address;
db.tblKullanici.Add(user);
db.tblAdres.Add(address);
db.SaveChanges();
if (db.SaveChanges() > 0)
{
Session["login"] = model.User;
return RedirectToAction("Index", "App");
}
}
ViewBag.Message = "Kayıt işlemi sırasında hata oluştu!";
return View(model);
}
jQuery
<script>
// ajax call to bring district and city info dynamically according to the city value
$(function () {
$.ajaxSetup({
type: "post",
url: "/User/IlIlce",// target
dataType: "json"
});
$.extend({
ilGetir: function () {
$.ajax({
//sending data
data: { "tip": "ilGetir" },
success: function (sonuc) {
//check result if ok then append it to selectlist
if (sonuc.ok) {
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#il").append(optionhtml);
});
} else {
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#il").append(optionhtml);
$("body").append(optionhtml);
});
}
}
});
},
ilceGetir: function (cityID) {
$.ajax({
// then we get the districts with cityID
data: { "ilID": cityID, "tip": "ilceGetir" },
success: function (sonuc) {
// deleting records
$("#ilce option").remove();
if (sonuc.ok) {
// disabled to false
$("#ilce").prop("disabled", false);
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#ilce").append(optionhtml);
});
} else {
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#ilce").append(optionhtml);
});
}
}
});
}
});
// invoke ilGetir to get city values
$.ilGetir();
// on change in city value
$("#il").on("change", function () {
// we get the id of selected value
var cityID = $(this).val();
// and pass it to the ilceGetir function to get the districts
$.ilceGetir(cityID);
});
});
</script>
and the method that ajax call goes:
public JsonResult IlIlce(int? ilID, string tip)
{
db = new DatabaseContext();
List<SelectListItem> sonuc = new List<SelectListItem>();
bool isSuccessful = true;
try
{
switch (tip)
{
case "ilGetir":
// we assign the city values in db to sonuc(result) variable
foreach (var sehir in db.tblSehir.ToList())
{
sonuc.Add(new SelectListItem
{
Text = sehir.sehirAdi,
Value = sehir.sehirID.ToString()
});
}
break;
case "ilceGetir":
// we will fetch districts with sehirID(cityID)
foreach (var ilce in db.tblİlce.Where(il => il.bagliOlduguSehirID == ilID).ToList())
{
sonuc.Add(new SelectListItem
{
Text = ilce.ilceAdi,
Value = ilce.ilceID.ToString()
});
}
break;
default:
break;
}
}
catch (Exception e)
{
// if we encounter an error
isSuccessful = false;
sonuc = new List<SelectListItem>();
sonuc.Add(new SelectListItem
{
Text = e.Message,
Value = "Default"
});
}
// i return the results as json
return Json(new { ok = isSuccessful, text = sonuc });
}
ilce means: district
sehir/il both means: city
sifre: password
kullaniciAdi: username
telefon: phone number
ulke: country
ilGetir : fetch city
ilceGetir: fetch district
kullanici: user
adres: address
sonuc: result
tip: type
I am going to pass external object list with form-data in submitHandler section. When i am passing form object only it is working properly. but i want to add list of object to that ajax post request.
JS
submitHandler: function (e) {
$(".loader-showhide").show();
var contacts = [
{ name: 'test 1', mobile: '11111111' },
{ name: 'test 2', mobile: '22222222' }
];
var dataToPost = JSON.stringify({ contacts: contacts });
var form = $(e);
form.find(":submit").attr("disabled", true);
$.ajax(form.attr("action"),
{
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: 'JSON',
data: { model: $(form).serialize(), contacts: dataToPost },
cache: false,
success(data) {
$(".loader-showhide").hide();
$("#myModal").modal('hide');
var table = $('#dt_account').DataTable();
table.ajax.reload();
toastr.success('Successfully added.');
$('#submitBtn').prop("disabled", false);
},
error(xhr) {
}
});
}
Controller
[HttpPost]
public ActionResult Create(ActivityViewModel model, List<Contact> contacts)
{
try
{
int result = 0;
return Json(new { StatusCode = result });
}
catch (Exception ex)
{
throw ex;
}
}
Object
public class Contact
{
public string Name { get; set; }
public string Mobile { get; set; }
}
Here is my form, I used jquery datatable and jquery form submit with submit handler.
<form action="#Url.Action("Create", "Activity")" id="account-form" method="POST" novalidate="novalidate" enctype="multipart/form-data">
<div class="form-blocker-wrap">
#Html.HiddenFor(o => o.Id)
<div class="card-block row">
<div class="col-lg-12">
<div class="scroller bottom-box px-3">
<div class="row">
<div class="col-lg-12 py-5 px-4 border-right">
<div class="col-md-6 form-group">
<label asp-for="Name">Activity Name</label>
#Html.TextBoxFor(o => o.Name, new { maxlength = 100, placeholder = "Campaign Name", #class = "form-control", required = "true" })
</div>
<div class="col-md-3 form-group">
<label asp-for="StartDateTime">Start Date</label>
#Html.TextBoxFor(o => o.StartDateTime, new { type = "date", maxlength = 100, placeholder = "Start Date", #class = "form-control", required = "true" })
</div>
<div class="col-md-3 form-group">
<label asp-for="EndDateTime">End Date</label>
#Html.TextBoxFor(o => o.EndDateTime, new { type = "date", maxlength = 100, placeholder = "End Date", #class = "form-control", required = "true" })
</div>
</div>
<div class="col-lg-12 py-5 px-4 border-right">
<div class="col-md-6 form-group">
<label asp-for="ContactType">Select Method</label><br />
#Html.DropDownListFor(o => o.ContactType, (IEnumerable<SelectListItem>)Model.ContactList, new { maxlength = 100, placeholder = "Campaign Name", #class = "form-control", #onchange = "ChangeMethod(this)", required = "true" })
</div>
</div>
<div class="col-lg-12 py-5 px-4 border-right">
<div disabled class="col-md-6 grl-section">
<div class="col-lg-12 form-group">
#for (int i = 0; i < Model.GRLContactGroupList.Count(); i++)
{
#Html.CheckBoxFor(m => m.GRLContactGroupList[i].IsChecked) #(#Model.GRLContactGroupList[i].GroupName + " - " + #Model.GRLContactGroupList[i].ZONE) <br />
#for (int j = 0; j < Model.GRLContactGroupList[i].GRLContactList.Count(); j++)
{
#Html.CheckBoxFor(m => m.GRLContactGroupList[i].GRLContactList[j].IsChecked) #Model.GRLContactGroupList[i].GRLContactList[j].Name <br />
}
}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card-footer modal-footer py-4">
<div class="row">
<div class="col-lg-6 px-4">
<button id="submitBtn" type="submit" class="btn btn-primary">Save</button>
<button type="reset" class="btn btn-default color-theme">Clear</button>
</div>
</div>
</div>
</form>
Controller
public ActionResult Isearch( string OFFICE_TYPE,string DEPARTMENT, string FILECATEGORY,string fromdate,string todate)
{
ViewBag.officetype = new SelectList(entity.TBL_OFFICETYPE.ToList(), "OFID", "OFFICE_TYPE");
//var list = new SelectList(entity.TBL_OFFICETYPE.Select(r => r.OFFICE_TYPE).ToList());
var list2 = new SelectList(entity.TBL_DEPARTMENT.Select(r => r.DEPARTMENTCODE).ToList());
ViewBag.department = list2;
var list4 = new SelectList(entity.TBL_FILECATEGORY.ToList(), "FILECATEGORY", "FILECATEGORY");
ViewBag.filecategory = list4;
var myinboxdata = entity.TBL_INBOX.ToList();
//var myinboxs = from res in entity.TBL_INBOX
// select new { res.OFFICETYPE, res.DEPARTMENTCODE, res.DESCRIPTION };
var myinbox1=from s in entity.TBL_INBOX select s;
if (String.IsNullOrEmpty(fromdate)&& String.IsNullOrEmpty(todate))
{
//DateTime fdate = Convert.ToDateTime(fromdate).Date;
//DateTime tdate = Convert.ToDateTime(todate).Date;
myinbox1 = entity.TBL_INBOX.Where(s => s.OFFICETYPE.Contains(OFFICE_TYPE) && s.DEPARTMENTCODE.Contains(DEPARTMENT) && s.FILECATEGORY.Contains(FILECATEGORY));
}
else
{
myinbox1 = entity.TBL_INBOX.Where(s => s.OFFICETYPE.Contains(OFFICE_TYPE) && s.DEPARTMENTCODE.Contains(DEPARTMENT) && s.FILECATEGORY.Contains(FILECATEGORY) && (s.UDATE >= Convert.ToDateTime(fromdate).Date && s.UDATE <= Convert.ToDateTime(todate)));
}
var data = myinbox1.OrderBy(x => x.OFFICETYPE).GroupBy(x => new { x.OFFICETYPE, x.DEPARTMENTCODE, x.DESCRIPTION }).Select(g => new { g.Key.OFFICETYPE, g.Key.DEPARTMENTCODE, g.Key.DESCRIPTION, Unread = g.Count() });
List<Inbox> mydata = new List<Models.Inbox>();
foreach (var myinbox in data)
{
mydata.Add(new Models.Inbox { OType = myinbox.OFFICETYPE, DCode = myinbox.DEPARTMENTCODE, Desc = myinbox.DESCRIPTION, Unread = myinbox.Unread });
}
ViewBag.data = mydata.ToList();
return View("Inbox");
}`enter code here`
In thee above code i passing the data from view. While passing the data i am getting the key for office type and department. Instead i want to get their value(text)
View
#using (Html.BeginForm("Isearch", "Transactions", FormMethod.Post))
{
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">My InBox</h3>
</div>
<div class="panel-body">
<div class="col-md-12 col-sm-12">
<div class="form-group col-md-4 col-sm-4">
<label for="Office">OfficeType</label>
#*#Html.DropDownList("officetype", ViewBag.officetype as SelectList, new { #class = "form-control input-sm", #id = "name" })*#
#Html.DropDownList("OFFICE_TYPE", ViewBag.officetype as SelectList, new { #class = "form-control input-sm", #id = "Office",name="Office" })
</div>
<div class="form-group col-md-4 col-sm-4" id="depart">
<label for="DEPARTMENT">Department</label>
#*#Html.DropDownList( ViewBag.Department,Enumerable.Empty<SelectListItem>(), new { #class = "form-control input-sm"})*#,
<select id="DEPARTMENT" name="DEPARTMENT" class = "form-control input-sm" ></select>
</div>
<div class="form-group col-md-4 col-sm-4">
<label for="FILECATEGORY">FILECATEGORY </label>
#Html.DropDownList("FILECATEGORY", ViewBag.filecategory as SelectList, new { #class = "form-control input-sm", #id = "name" })
</div>
<div class="form-group col-md-4 col-sm-4">
<label>From Date</label>
#Html.TextBox("fromdate", null, new { #id = "fromdate", #class = "form-control input-sm" })
#*<input name="fdate" type="text" id="fromdate" class="form-control input-sm" />*#
</div>
<div class="form-group col-md-4 col-sm-4">
<label>To Date</label>
#Html.TextBox("todate", null, new { #id = "todate", #class = "form-control input-sm" })
#*<input type="text" id="todate" class="form-control input-sm" />*#
</div>
<div class="form-group col-md-4 col-sm-4">
<br />
<input type="submit" value="Search" class="btn btn-primary" />
</div>
</div>
</div>
</div>
}
the above code is view code where i an passing the value through the id and name property.
In thee above code i passing the data from view. While passing the data i am getting the key for office type and department. Instead i want to get their value(text)
Giving you an example:
<select id="drpgenderid" name="drpgendername">
<option value="1">#Html.Label("FEMALE",Model.gender, new { #style = "", #id = "new_id_gender", #name = "name_new_gender", #placeholder = "Gender", #enabled = "false", #value = "FEMALE" })</option>
<option selected="selected" value="2">#Html.Label("MALE",Model.gender, new { #style = "", #id = "new_id_gender", #name = "name_new_gender", #placeholder = "Gender", #enabled = "false", #value = "MALE" })</option>
</select>
SCRIPT
function GetData()
{
var pdrp = document.getElementById("drpgenderid");
gender = pdrp.options[pdrp.selectedIndex].value;
}
using AJAX
GetData();
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
url: "#Url.Action("GetDemoData")",
data: "{'gender':'" + gender.trim() + "'}",
success: function (data) {
}
});
CONTROLLER
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetDemoData(String gender)
{
string gtGender = gender;
}
use ViewBag and #Html.DropDownList we can do drop-down without using model data
In controller
public ActionResult dropdown() {
var customers = new List<Customer>();
customers.Add(new Customer { Name = "Airi Satou", ID = 1 });
customers.Add(new Customer { Name = "Brenden Wagner", ID = 2 });
customers.Add(new Customer { Name = "Brielle Williamson", ID = 2 });
ViewBag.DropData = customers;
return View();
}
In View
#Html.DropDownList("CustomerDropDown", new SelectList(ViewBag.DropData, "ID", "Name"), new { #class="form-control"})
#Html.DropDownList("CustomerDropDown2", new SelectList(ViewBag.DropData, "Name", "Name"), new { #class="form-control"})
I would like to put uploadify in the website I'm making so that I can see the progress of the files that being attach. So I search on how to do that, I know I'm doing something wrong that's why it's not working(the progress doesn't show). Please help me, I'm new with this kind of stuff. Thank you. Here's my controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(EmailFormModel model, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
List<string> paths = new List<string>();
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/uploads"), fileName);
file.SaveAs(path);
paths.Add(path);
}
}
var message = new MailMessage();
foreach (var path in paths)
{
var fileInfo = new FileInfo(path);
var memoryStream = new MemoryStream();
using (var stream = fileInfo.OpenRead())
{
stream.CopyTo(memoryStream);
}
memoryStream.Position = 0;
string fileName = fileInfo.Name;
message.Attachments.Add(new Attachment(memoryStream, fileName));
}
//Rest of business logic here
string EncodedResponse = Request.Form["g-Recaptcha-Response"];
bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false);
if (IsCaptchaValid)
{
var body = "<p>Email From: {0} ({1})</p><p>Subject: {2} </p><p>Message:</p><p>{3}</p>";
message.To.Add(new MailAddress("***#gmail.com")); // replace with valid value
message.From = new MailAddress("***#ymailcom"); // replace with valid value
message.Subject = "Your email subject";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.FromSubject, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "***#gmail.com", // replace with valid value
Password = "***" // replace with valid value
};
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
ViewBag.Message = "Your message has been sent!";
ModelState.Clear();
return View("Index");
}
}
else
{
TempData["recaptcha"] = "Please verify that you are not a robot!";
}
}
return View(model);
}
public ActionResult Upload()
{
var file = Request.Files["Filedata"];
string savePath = Server.MapPath(("~/uploads") + file.FileName);
file.SaveAs(savePath);
return Content(Url.Content(("~/uploads") + file.FileName));
}
And here's the script that I add to my _Layout.cshtml :
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/UploadifyContent/jquery.uploadify.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/UploadifyContent/jquery.uploadify.min.js")"></script>
<link rel="stylesheet" type="text/css" href="#Url.Content("~/Content/UploadifyContent/uploadify.css")" />
<script type="text/javascript">
$(function () {
$('#file_upload').uploadify({
'swf': "#Url.Content("~/Content/UploadifyContent/uploadify.swf")",
'cancelImg': "#Url.Content("~/Content/UploadifyContent/uploadify-cancel.png")",
'uploader': "#Url.Action("Upload", "Home")",
'onUploadSuccess': function (file, data, response) {
$("#uploaded").append("<img src='" + data + "' alt='Uploaded Image' />");
}
});
});
</script>
And here's my view:
#using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="col-md-4">
<div class="contact_form block">
<div class="row">
<div class="col-md-12 col-sm-12">
<div id="note"></div>
</div>
</div>
<div id="fields">
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromName)
#Html.TextBoxFor(m => m.FromName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromName, null, new { #class = "text-danger" })
</div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromEmail)
#Html.TextBoxFor(m => m.FromEmail, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromEmail, null, new { #class = "text-danger" })
</div>
<div class="clear"></div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromSubject)
#Html.TextBoxFor(m => m.FromSubject, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromSubject, null, new { #class = "text-danger" })
</div>
<div class="col-md-12 col-sm-6">
<form action="" method="post" enctype="multipart/form-data">
<label for="file1">Attachments</label>
<input type="file" name="files" id="file1" multiple />
</form>
<div id="uploaded"></div>
</div>
<div class="col-md-12">
#Html.LabelFor(m => m.Message)
#Html.TextAreaFor(m => m.Message, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message, null, new { #class = "text-danger" })
</div>
<div class="col-md-12">
<div>
#if ((TempData["recaptcha"]) != null)
{
<p>#TempData["recaptcha"]</p>
}
</div>
<div class="g-recaptcha" data-sitekey="6LfVHx8TAAAAAMTDxxQrHDCxO1SyXf1GgbgNBZ5a"></div>
</div>
<div class="col-md-12"><input class="shortcode_button" type="submit" value="Send"></div>
</div>
</div>
</div>
}
As can be seen in this picture I have a list of missing dates I have not reported a time for, and when I click a date I have missed my 'Rappotera tid' gets filled in with that date.
But what I want to do is I want to remove my 'Datum' have it sole based on the check boxes that are before the date, so at at a later date can report several dates at once.
But I am stuck and I would like to get some help.
This is my view:
<script type="text/javascript" language="javascript">
$(function() {
$(function() {
$('#date').datepicker({
showButtonPanel: true,
changeMonth: true,
changeYear: true,
dateFormat: "yy-mm-dd",
firstDay: 1,
onSelect: function(dateText) {
$('#EndDate').datepicker('option', 'minDate', new Date(dateText));
}
});
});
});
function SetDate(dt) {
$('#date').val(dt);
}
var n = #(Model.Projects.Count);;
function AddProject() {
n++;
$.ajax({
type: "GET",
url: "#Url.Action("Project")/" + n,
dataType: "html",
success: function(data) {
$('#projects').append(data);
}
});
}
$(function() {
$('#startTime').change(function() { CalculateTime(); });
$('#endTime').change(function() { CalculateTime(); });
$('#breakTime').change(function() { CalculateTime(); });
CalculateTime();
});
function CalculateTime() {
try {
var startTime = $('#startTime').val();
var endTime = $('#endTime').val();
var breakTime = $('#breakTime').val();
var startDate = new Date(2000, 1, 1, startTime.substring(0, 2), startTime.substring(3, 5), 0, 0);
var endDate = new Date(2000, 1, 1, endTime.substring(0, 2), endTime.substring(3, 5), 0, 0);
var time = endDate - startDate;
time = time / 1000 / 60 / 60;
time = time - breakTime.substring(0, 2);
time = time - (breakTime.substring(3, 5) / 60);
$('#workedHours').html(time + " timmar");
} catch (err) {
$('#workedHours').html("---");
}
}
</script>
<div class="page-container">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
#if (ViewData["posted"] != null)
{
<div class="alert alert-success">
<strong>Tidsrapporten tillagd.</strong>
</div>
}
<div class="tabbable tabbable-custom tabbable-noborder tabbable-reversed">
<div class="tab-content">
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-green-sharp bold uppercase">missad rappoterad tid</span>
</div>
</div>
<form class="form-horizontal">
<div class="portlet-body form">
<div class="form-group">
#foreach (var date in ViewBag.MissingDays)
{
var isoDate = date.ToString("yy-MM-dd");
<div class="col-md-1">
<input type="checkbox" name="Date" value="Date">
#isoDate
</div>
}
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#Html.ValidationSummary()
#using (Html.BeginForm("TimeReport", "Reports", FormMethod.Post, new { enctype = "multipart/form-data", #class = "form-horizontal" }))
{
#Html.Hidden("ReportId", Model.ReportId)
<div class="col-md-6">
<div class="tabbable tabbable-custom tabbable-noborder tabbable-reversed">
<div class="tab-content">
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-green-sharp bold uppercase">Rappotera tid</span>
</div>
</div>
<div class="portlet-body form">
<div class="form-group">
<label class="col-md-3 control-label">Datum:</label>
<div class="col-md-5">
#Html.TextBox("date", Model.Date.ToShortDateString(), new {#class = "form-control"})
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Start tid:</label>
<div class="col-md-5">
#Html.TextBox("startTime", Model.Times.StartTime, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Slut tid:</label>
<div class="col-md-5">
#Html.TextBox("endTime", Model.Times.EndTime, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Rast Längd:</label>
<div class="col-md-5">
#Html.TextBox("breakTime", Model.Times.BreakTime, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Tid jobbad:</label>
<div class="col-md-5">
#Html.TextBox("workedHours", Model.Times.WorkedHours, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div id="projects">
#foreach (var data in Model.Projects)
{
Html.RenderPartial("Project", data, ViewData["vd"] as ViewDataDictionary);
var viewDataDictionary = ViewData["vd"] as ViewDataDictionary;
if (viewDataDictionary != null)
{
viewDataDictionary["id"] = (int)viewDataDictionary["id"] + 1;
}
}
</div>
</div>
<div class="form-actions">
<div class="col-md-offset-4 col-asdfasmd-9">
Lägg till projekt
<button type="submit" class="btn btn-primary">Spara</button>
</div>
</div>
if (Model.ReportId.HasValue)
{
<input type="submit" value="Ta bort" name="delete" />
}
}
</div>
</div>
</div>
</div>
And this is my controller for this view:
public ActionResult TimeReport(FormCollection form, Guid? id)
{
ViewDataDictionary vd = new ViewDataDictionary
{
["projects"] = new DatabaseLayer().GetConsultantProjects(Constants.CurrentUser(User.Identity.Name)),
["id"] = 1,
["showDescription"] = true
};
ViewData["vd"] = vd;
NewTimeReportModel projectData = new NewTimeReportModel();
if (form != null && form.AllKeys.Contains("delete"))
{
new DatabaseLayer().DeleteTimeReport(Guid.Parse(form["ReportId"]));
LoadDefaultSettings(projectData);
ViewData.Model = projectData;
return View();
}
if (id.HasValue && (form == null || form.AllKeys.Length == 0))
{
using (DatabaseLayer db = new DatabaseLayer())
{
var timeReport = db.GetTimeReport(id.Value);
projectData = new NewTimeReportModel(timeReport);
if (projectData.Projects.Count == 1)
projectData.Projects[0].Hours = null;
}
}
else if (form == null || form.AllKeys.Length == 0)
{
LoadDefaultSettings(projectData);
}
else
{
DateTime reportDate;
if (!DateTime.TryParse(form["date"], out reportDate))
ModelState.AddModelError("Date", "Felaktikt datum");
var projectNumbers = (from x in form.AllKeys
where x.Contains("_")
select x.Substring(x.IndexOf('_'))).Distinct();
projectData.Times = new TimeReportTimes(form["startTime"], form["endTime"], form["breakTime"], ModelState);
projectData.Date = reportDate;
if (!projectNumbers.Any())
ModelState.AddModelError("Projekt", "Inga projekt valda...");
else
{
int emptyHours = 0;
foreach (string projectNumber in projectNumbers)
{
projectData.Projects.Add(new NewTimeReportModel.Project
{
Description = form["description" + projectNumber],
Hours = null,
ProjectId = Guid.Parse(form["project" + projectNumber])
});
string hourString = form["hours" + projectNumber];
if (string.IsNullOrEmpty(hourString))
{
emptyHours++;
projectData.Projects[projectData.Projects.Count - 1].Hours = projectData.Times.WorkedHours;
}
else
{
if (!projectData.Projects[projectData.Projects.Count - 1].SetHours(hourString))
{
ModelState.AddModelError("hours_" + projectNumber, "Felaktig antal timmar");
}
}
}
if (emptyHours > 1 || (emptyHours == 0 && projectData.Projects.Sum(x => x.Hours) != projectData.Times.WorkedHours))
{
ModelState.AddModelError("hours_" + projectNumbers.First(), "Antalet timmar stämmer ej överrens");
}
if (projectData.Projects.Where(x => x.Hours <= 0).Any())
{
ModelState.AddModelError("hours_" + projectNumbers.First(), "Antalet timmar måste vara större än noll");
}
if (!string.IsNullOrEmpty(form["ReportId"]))
projectData.ReportId = Guid.Parse(form["ReportId"]);
if (ModelState.IsValid)
{
projectData.SaveToDatabase(Constants.CurrentUser(User.Identity.Name));
ViewData["posted"] = true;
projectData = new NewTimeReportModel();
LoadDefaultSettings(projectData);
}
else if (projectData.Projects.Count == 1)
projectData.Projects[0].Hours = null;
}
}
var missingdays = new DatabaseLayer().GetConsultantMissingDays(Constants.CurrentUser(User.Identity.Name));
if (missingdays.Count == 0)
{
ViewData["missingDays"] = "";
}
else
{
ViewBag.MissingDays = missingdays;
}
ViewData.Model = projectData;
return View();
}