HTML.BeginForm doesn't call the proper action - asp.net-mvc-4

I have a this part in Edit.chtml looks like
#using (#Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<article class="SearchBoxCon clearfix">
#if (Model.Entity.Document == null)
{
using (Html.BeginForm("AudioUpload", "Noun", FormMethod.Post, new { enctype = "multipart/form-data", NounId = Model.Entity.Id }))
{
<article class="BtnCon">
<article class="BrowseBtn">
<input type="file" value="Browse" name="file">
</article>
<article class="BrowseUpload">
<input type="submit" id="AudioUpload" value="AudioUpload">
</article>
</article>
}
}
else
{
<article class="inputBTn">
<input type="submit" value="Play">
<input type="submit" value="Delete">
</article>
}
</article>
<article class="inputBTn">
<input type="submit" value="Save">
</article>
<!-- submit btn ends here -->
#Html.ActionLink("Back to List", "Index", "Noun/Index", null, new { #class = "BackList" })
</article>
}
after browsing and upload the file , and click the upload it fire the edit posting action instead of the uploadaudio which looks like
[HttpPost]
public ActionResult AudioUpload(HttpPostedFileBase file , int NounId )
{

[ActionName("Edit")] put attribute on your action method it will work
[HttpPost, ActionName("Edit")]
public ActionResult AudioUpload(HttpPostedFileBase file , int NounId )
{
make you code like this if your view name is Edit.cshtml

Try like this,
#if (Model.Entity.Document == null)
{
using (Html.BeginForm("AudioUpload", "Noun", FormMethod.Post, new { enctype = "multipart/form-data", NounId = Model.Entity.Id,Id="frmAudioUpload" }))
{<article class="BtnCon">
<article class="BrowseBtn">
<input type="file" value="Browse" name="file">
</article>
<article class="BrowseUpload">
<input type="button" id="AudioUpload" value="AudioUpload">
</article>
</article>
}}
Script
<script type="text/javascript">
$(function(){
$('#AudioUpload').click(function(){
$('#frmAudioUpload').submit();
});
});
</script>

Related

In my creation process I want to write to another entity than only the used

If I submit the page the first save goes without a problem
Than I assigned all values to the other entity which I want to write to create there a new record.
Why do I get an System Null Reference. I have in all fields the values which I want?
[
=== here is my c# Code ===========
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using WorkCollaboration.Data;
using WorkCollaboration.Models;
namespace WorkCollaboration.Pages.TimeReports
{
public class CreateModel : PageModel
{
private readonly WorkCollaboration.Data.WorkCollaborationContext _context;
public CreateModel(WorkCollaboration.Data.WorkCollaborationContext context)
{
_context = context;
}
public IActionResult OnGet()
{
CusContactDropDownDisp = _context.CusContactDropDown.ToList(); // Added for DropDown
SupContactDropDownDisp = _context.SupContactDropDown.ToList(); // Added for DropDown
return Page();
}
[BindProperty]
public TimeReport TimeReport { get; set; }
public IEnumerable<Models.CusContactDropDown> CusContactDropDownDisp { get; set; }
public IEnumerable<Models.SupContactDropDown> SupContactDropDownDisp { get; set; }
public Models.PointsforSupContact PointsforSupContact { get; set; }
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
TimeReport.TimeReportSupContactPointValue = (TimeReport.TimeReportHours * 10);
_context.TimeReport.Add(TimeReport);
await _context.SaveChangesAsync();
//============================================
// Adding new Point Record to Supplier Contact
//============================================
PointsforSupContact.PointsId = TimeReport.TimeReportId;
PointsforSupContact.PointsSupContactId = TimeReport.TimeReportSupplierTalentContactId;
PointsforSupContact.PointsInternalUserId = 1; // User 1 Christof Oberholzer must be entered in Contacts and User
PointsforSupContact.PointsDate = TimeReport.TimeReportDate;
PointsforSupContact.PointsTotal = TimeReport.TimeReportSupContactPointValue;
PointsforSupContact.PointsText = TimeReport.TimeReportText;
PointsforSupContact.PointsTitle = "TimeReporting Points";
_context.PointsforSupContact.Add(PointsforSupContact);
await _context.SaveChangesAsync();
return RedirectToPage("/TimeReportOverview/Index");
}
}
}
==== My Page ======
#page
#using Microsoft.AspNetCore.Localization
#using Microsoft.AspNetCore.Mvc.Localization
#model WorkCollaboration.Pages.TimeReports.CreateModel
#{
ViewData["Title"] = "Create";
ViewData["RandomId"] = Guid.NewGuid().GetHashCode();
}
#inject IViewLocalizer Localizer
<h1>Create</h1>
<h4>TimeReport</h4>
<p>
<a asp-page="/TimeReportOverview/Index">Back to Index</a>
</p>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="TimeReport.TimeReportSupContactPointValue" value="0"/>
<div class="form-group">
<label asp-for="TimeReport.TimeReportId" class="control-label"></label>
<input asp-for="TimeReport.TimeReportId" value='#ViewData["RandomId"]' readonly="readonly" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeReport.TimeReportCustomerNeedContactId" class="control-label"></label>
</div>
<select id="CusContactId" asp-for="CusContactDropDownDisp" asp-items="#(new SelectList(Model.CusContactDropDownDisp,"CusContactId","CusFullName"))">
<option value="" selected disabled>--Choose Customer--</option>
</select>
<div class="form-group">
<input asp-for="TimeReport.TimeReportCustomerNeedContactId" readonly="readonly" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportCustomerNeedContactId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeReport.TimeReportSupplierTalentContactId" class="control-label"></label>
</div>
<select id="SupContactId" asp-for="SupContactDropDownDisp" asp-items="#(new SelectList(Model.SupContactDropDownDisp,"SupContactId","SupFullName"))">
<option value="" selected disabled>--Choose Supplier--</option>
</select>
<div class="form-group">
<input asp-for="TimeReport.TimeReportSupplierTalentContactId" readonly="readonly" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportSupplierTalentContactId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeReport.TimeReportDate" class="control-label"></label>
<input type="datetime-local" asp-for="TimeReport.TimeReportDate" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeReport.TimeReportHours" class="control-label"></label>
<input asp-for="TimeReport.TimeReportHours" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportHours" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TimeReport.TimeReportText" class="control-label"></label>
<input asp-for="TimeReport.TimeReportText" class="form-control" />
<span asp-validation-for="TimeReport.TimeReportText" class="text-danger"></span>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TimeReport.TimeReportState, htmlAttributes: new { #class = "form-group" })
<div class="form-group">
#Html.DropDownListFor(model => model.TimeReport.TimeReportState, new List<SelectListItem>
{
new SelectListItem {Text = "Gebucht", Value = "Reported", Selected = true },
new SelectListItem {Text = "Kontrolliert", Value = "Controlled" },
new SelectListItem {Text = "Verrechnet / Noch nicht bezahlt", Value = "Invoiced / Not yet payed" },
new SelectListItem {Text = "Verrechnet / Bezahlt", Value = "Invoiced / Payed" },
}, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TimeReport.TimeReportState, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
Back to List
</div>
</form>
</div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script>
$("#CusContactId").on("change", function () {
$("#TimeReport_TimeReportCustomerNeedContactId").val($("#CusContactId").val());
});
$("#SupContactId").on("change", function () {
$("#TimeReport_TimeReportSupplierTalentContactId").val($("#SupContactId").val());
});
</script>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Thank you for your help
First In your view:
ViewData["RandomId"] = Guid.NewGuid().GetHashCode();
GetHashCodemethod make the Guid to int,please make sure it matches the type in your model.
Then the right way to add new PointsforSupContact is to create a new PointsforSupContact,so you need to delete the code:
public Models.PointsforSupContact PointsforSupContact { get; set; }
and change you code to:
//...
await _context.SaveChangesAsync();
//add this line
var PointsforSupContact=new PointsforSupContact();
PointsforSupContact.PointsId = TimeReport.TimeReportId;
//...

Posting checkbox to controller MVC 5/ ASP.NET Core

I'm trying to post checkbox information back to the controller so I can save update the data in the database. Currently, I have all the values on the page, but when I check or uncheck the box it never goes to the controller.
Controller
[HttpPost]
public void SaveSettings(SettingsListModel SettingsModel)
{
DataLayer dl = new DataLayer();
}
View
#model WebApplication1.Models.SettingsListModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="#Url.Content("~/Scripts/app.js")"></script>
<title>Settings</title>
</head>
<body>
<h1>Settings</h1>
<div>
<form asp-action="SaveSettings" asp-controller="Home" method="post">
<div align="center">
<div align="center">
#for (int i = 0; i < Model.listOfSettings.Count; i++)
{
#Html.HiddenFor(m => m.listOfSettings.ElementAt(i).settingID)
#Html.HiddenFor(m => m.listOfSettings.ElementAt(i).settingText)
<div>
#Html.DisplayTextFor(m => m.listOfSettings.ElementAt(i).settingText)
</div>
<div>
//#Html.HiddenFor(m => m.listOfSettings.ElementAt(i).settingsSelected)
#Html.CheckBoxFor(m => m.listOfSettings.ElementAt(i).settingsSelected)
</div>
<br />
<br />
<br />
}
</div>
</div>
</form>
</div>
</body>
</html>
Model
public class SettingsListModel
{
public List<SettingsModel> listOfSettings { get; set; }
}
public class SettingsModel
{
public int settingID { get; set; }
public string settingText { get; set; }
public bool settingsSelected { get; set; }
}
You cannot use .ElementAt() in your expressions - it is generating name attributes that have no relationship to your model. Since the property is List<T>, then just use the collection indexer
#for (int i = 0; i < Model.listOfSettings.Count; i++)
{
#Html.HiddenFor(m => m.listOfSettings[i].settingID)
#Html.HiddenFor(m => m.listOfSettings[i].settingText)
<div>
#Html.DisplayTextFor(m => m.listOfSettings[i].settingText)
</div>
<div>
#Html.CheckBoxFor(m => m.listOfSettings[i].settingsSelected)
</div>
}
Your <form> element is also missing a submit button to post the values to the controller.
Enumerable.ElementAt() returns a type (its return type is TSource), not the property name which must be added in name attribute. Use the collection property indexer instead:
<form asp-action="SaveSettings" asp-controller="Home" method="post">
<div align="center">
<div align="center">
#for (int i = 0; i < Model.listOfSettings.Count; i++)
{
#Html.HiddenFor(m => m.listOfSettings[i].settingID)
#Html.HiddenFor(m => m.listOfSettings[i].settingText)
<div>
#Html.DisplayTextFor(m => m.listOfSettings[i].settingText)
</div>
<div>
#Html.CheckBoxFor(m => m.listOfSettings[i].settingsSelected)
</div>
<br />
<br />
<br />
}
</div>
</div>
<!-- add a button here to submit the form -->
<button type="submit">Submit</button>
</form>
Tag helper version:
<form asp-action="SaveSettings" asp-controller="Home" method="post">
<div align="center">
<div align="center">
#for (int i = 0; i < Model.listOfSettings.Count; i++)
{
<input asp-for="listOfSettings[i].settingID" type="hidden" />
<input asp-for="listOfSettings[i].settingText" type="hidden" />
<div>
#Html.DisplayTextFor(m => m.listOfSettings[i].settingText)
</div>
<div>
<input asp-for="listOfSettings[i].settingsSelected" type="checkbox" />
</div>
<br />
<br />
<br />
}
</div>
</div>
<!-- add a button here to submit the form -->
<button type="submit">Submit</button>
</form>
Also you need to replace return type from void to ActionResult (or IActionResult if .NET Core is used):
[HttpPost]
public ActionResult SaveSettings(SettingsListModel SettingsModel)
{
DataLayer dl = new DataLayer();
// do something
return View(model);
}

bootstrap modal form cannot edit on smartphone

I have a modal window that works fine on laptop..
On a smart phone, as soon as I click any input field (to edit), the modal disappears, and page reloads...
What is causing this behavior ?
<div class='modal fade my_modal' id='edit-member-container' tabindex='-1' role='dialog' aria-hidden='true'>
<div class='modal-dialog'>
<div class='row'>
<div class='col-sm-6 col-centered'>
<form id='contact' action='' method='post'>
<h3>Edit</h3>
<fieldset>
<input placeholder='First Name' type='text' tabindex='1' id='txtFname' value='$first_name'>
</fieldset>
<fieldset>
<input placeholder='Last Name' type='text' tabindex='2' id='txtLname' value='$last_name'>
</fieldset>
<fieldset>
<button type='button' id='btnsaveEdit'>Save Changes</button>
</fieldset>
</form>
</div><!-- col -->
</div><!-- row -->
</div><!-- dialog -->
</div> <!-- close edit member modal -->
<script>
$(document).on("click","#btnsaveEdit",function(){
var id_key = $("#id_key").val();
var first_name = $("#txtFname").val();
var last_name = $("#txtLname").val();
var value = {
id_key:id_key,
first_name:first_name,
last_name:last_name
};
$.ajax(
{
url : "http://www.clubsandgroups.com/new-crud/application/member/save_user_edit_member_3.php",
method: "POST",
data : value,
dataType : "JSON",
success: function(response)
{ ... }
});
});
</script>

Upload file to chosen folder

I have radio buttons with the folder name. A user can choose a folder name where he/she wants to upload a file. then he/she choose the folder name and upload the file
this is the model:
public class UploadViewModel
{
public string Id { get; set; }
[Required]
[Display(Name = "FormToUpload", ResourceType = typeof(Resources.Entity.Form))]
public HttpPostedFileBase UploadData { get; set; }
private UploadModel _uploadModel;
public string[] Directories { get; set; }
public bool? IsActive { get; set; }
public UploadViewModel(UploadModel uploadModel)
{
_uploadModel = uploadModel;
}
}
this the method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadFile([Bind(Include = "UploadData")] LibraryUploadModel libraryUpload, string designId, string[] selectedFile)
{
TemplateLibraryEntry entry = GetTemplateLibraryEntry(designId, customerSchema);
var path = Path.Combine(Server.MapPath("~/"), entry.FilePath);
if (Request != null)
{
//HttpPostedFileBase file = Request.Files["UploadData"];
if ((libraryUpload.UploadData != null) && (libraryUpload.UploadData.ContentLength > 0) && !string.IsNullOrEmpty(libraryUpload.UploadData.FileName))
{
var fileName = Path.GetFileName(libraryUpload.UploadData.FileName);
//var path = Path.Combine(Server.MapPath("~/img/Data"), fileName);
libraryUpload.UploadData.SaveAs(path);
}
}
return View();
}
and this is the view:
#model SenecaFormsServer.Areas.Dashboard.Models.UploadViewModel
ViewBag.Title = Resources.Entity.DesignTemplate.UploadForm;
}
#Html.Partial("~/Areas/_Shared/_BreadCrumbsPartial.cshtml")
<!-- widget grid -->
<section id="widget-grid">
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-xs-12 ">
#Html.RenderNotifications()
</div>
<div class="col-xs-12 padding-bottom-10">
<button type="submit" value="UploadFile" class="btn btn-success"><i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.Upload</button>
<i class="fa fa-fw fa-times"></i>#Resources.Action.Navigation.Cancel
</div>
</div>
<div class="well no-padding">
<div class="bg-color-white">
<div class="row padding-10">
<div class="col-xs-12">
<h4>#Resources.Entity.DesignTemplate.FileName</h4>
</div>
<div class="col-xs-12 margin-bottom-10 margin-top-10">
<div class="form-horizontal">
#Html.ValidationSummary(true)
#*<div class="form-group">
#Html.LabelFor(model => model.UploadData, new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10">
<input name="#Html.NameFor(model => model.UploadData)" type="file" />
#Html.ValidationMessageFor(model => model.UploadData)
</div>
</div>*#
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<table>
#foreach (var item in Model.Directories)
{
<tr>
<td>
#Html.RadioButton("Assigned", Model.IsActive.HasValue ? Model.IsActive : false);
#Html.Label(item)
</td>
</tr>
}
</table>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UploadData, new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10">
<input name="#Html.NameFor(model => model.UploadData)" type="file" />
#Html.ValidationMessageFor(model => model.UploadData)
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
</section>
<!-- end widget grid -->
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Thank you
If i now try to upload I get this error:
Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 746: {
Line 747: TemplateLibraryEntry entry = GetTemplateLibraryEntry(designId, customerSchema);
Line 748: var path = Path.Combine(Server.MapPath("~/"), entry.FilePath);
Line 749:
Line 750: foreach (var item in uploadViewModel)
Source File: b:\Seneca\Producten\FormsServer\Trunk\SenecaFormsServer\Areas\Dashboard\Controllers\DesignTemplateController.cs

Include Local javascript file with global dependency for only a view

I have a view like this
#model IEnumerable<DuckingOctoBear.Models.PostViewModel>
<p>
#if (User.IsInRole("Administrator") || User.IsInRole("Editor"))
{
#Html.ActionLink("Create New", "Create")
}
</p>
<div class="">
#foreach (DuckingOctoBear.Models.PostViewModel item in Model)
{
<a href="/Posts/Details/#item.Post.Id" class="post-element">
<h4>#Html.DisplayFor(modelItem => item.Post.Title)</h4>
<h6>
Inserted by #item.User.UserName at #item.Post.Date.ToString("dd MMMM yyyy hh:ss")
</h6>
<article>
#Html.Raw(item.Post.Text)
</article>
<span>
#if (User.IsInRole("Administrator") || User.IsInRole("Editor"))
{
#Html.ActionLink("Edit", "Edit", new { id = item.Post.Id })
<span>|</span>
}
#Html.ActionLink("Details", "Details", new { id = item.Post.Id })
<span>|</span>
#if (User.IsInRole("Administrator"))
{
#Html.ActionLink("Delete", "Delete", new { id = item.Post.Id })
<span>|</span>
}
</span>
</a>
}
</div>
...where I would like include a Javascript file which have strong dependencies to other Javascript files already included in the _Layout.cshtml
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
How can I include that local file without register it in a bundle, and so for all views?
Ok epic fail
for this _Layout.cshtml
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
I could add just a new section
#RenderSection("LocallyScriptLibrary", required: false)
then in the target view doing just:
#section LocalScriptLibrary{
<script src="~/Scripts/LocalLibrary.js"></script>
}