in .net MVC 5 with razor syntax I am trying to update the file but after click on update, the file name is not showing inside the textbox, for more clear picture please refer the image,
cshtml code is
<div class="form-group">
#Html.ReqLabelFor(model => model.file_path, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-5 offset-md-5">
#*#Html.TextBox("upload", null, new { type = "file", accept = "image/*", #class = "form-control" })*#
#Html.TextBox("file", null, new { type = "file", #class = "form-control" })
#Html.ValidationMessageFor(model => model.file_path, "", new { #class = "text-danger" })
</div>
</div>
And c# code is
File fileDownload = await db.File.Where(x => x.id == id).FirstOrDefaultAsync();
where file_path is of string type.
But actually It should come like below image
Related
My editorfor onChangeEvent isn't working and I can't figure out why.
here is my javascript function
<script type="text/javascript">
function OnChangeEvent() {
alert("value is changed");
var compQty = $('#compQTY').val();
//do other functions here also like change button
//if decrease add below
if (compQty < #Model.comp_qty) {
btn.Attributes.Add("onclick", "clicked(event)");
}
}
<script>
and here is my editorFor
<div class="form-group">
#Html.LabelFor(model => model.comp_qty, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#if (ViewBag.isValid == false)
{
#Html.TextBoxFor(model => model.comp_qty, new { disabled = "disabled", #Value = Model.comp_qty, #readonly = "readonly" })
}
else
{
#Html.EditorFor(model => model.comp_qty, new { htmlAttributes = new { onchange = "OnChangeEvent(this)", min = 0, #class = "form-control", #id = "compQTY" } })
#Html.ValidationMessageFor(model => model.comp_qty, "", new { #class = "text-danger" })
}
</div>
</div>
from what I have googled this should work but it is not. Can anybody help me figure out what I'm missing or what the possible solution is?
This question already has an answer here:
Submit same Partial View called multiple times data to controller?
(1 answer)
Closed 5 years ago.
I have a drop-down list (where multiple options can be selected) and two input boxes inside another div with id 'showInvestmentForm'.Upon selection of drop-down items,I want to produce those text boxes with respect to the number of drop-down items selected.
I want these text boxes to have different Names but I cant find a way to provide them different Names in such a way that their input values get passed to the controller.
This is a part of my Controller:-
foreach(var data in propertyViewModel.PropertyInvestors)
{
FounderInvestment founderInvestment = new FounderInvestment
{
Id = propertyViewModel.FounderInvestmentViewModel.Id ?? 0,
InstallmentPeriod = propertyViewModel.FounderInvestmentViewModel.InstallmentPeriod,
InvestorId = Convert.ToInt32(data),
PropertyId = property.Id,
Investment = propertyViewModel.FounderInvestmentViewModel.Investment
};
_founderInvestmentQueryProcessor.Create(founderInvestment);
}
This is my dropdown:-
<div class="form-group">
#Html.LabelFor(model => model.PropertyInvestors, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.PropertyInvestors, (IEnumerable<SelectListItem>)#ViewBag.Investors, "Select", htmlAttributes: new {#id="dropdown", #class = "form-control",#multiple="multiple" })
#Html.ValidationMessageFor(model => model.PropertyInvestors, "", new { #class = "text-danger" })
</div>
</div>
These are the textboxes:-
<div id="showInvestmentForm" style="display:none">
<div class="form-group">
#Html.LabelFor(model => model.FounderInvestmentViewModel.Investment, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FounderInvestmentViewModel.Investment, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FounderInvestmentViewModel.Investment, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FounderInvestmentViewModel.InstallmentPeriod, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FounderInvestmentViewModel.InstallmentPeriod, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FounderInvestmentViewModel.Investment, "", new { #class = "text-danger" })
</div>
</div>
</div>
If I understood correctly your problem is that input texts are not posted to your Controller.
Would be usefult if you write the Controller's code to check the full scenario.
Anyway a common mistake, that could be your case, when using Mvc helpers is that when you point to a nested property, the generated name of the input is not the final property name but a path to that property.
#Html.EditorFor(model => model.FounderInvestmentViewModel.InstallmentPeriod, ..)
In your case that code produce an input with name FounderInvestmentViewModel_InstallmentPeriod, and not just InstallmentPeriod.
If in your controller you expect a parameter named "InstallmentPeriod" that would not be received, because the page posts a parameter named "FounderInvestmentViewModel_InstallmentPeriod"
I'm using Entity Framework 7 with ASP.NET MVC 5.
I have some forms that look like this. Clicking on one of the "new" buttons brings up a Bootstrap modal that looks like this. Submitting the modal form adds a new entity to the database before appending its name and primary key to the selectlist.
This works, but if the user changes their mind, the item(s) created via the modal (location in this case) stick around forever. So ideally none of the child items would be created until the main form is finished. While the example only has two simple fields, other data models have more than half a dozen, which may include complex fields of their own (but preventing that wouldn't be a horrible restriction).
So what's the best way to do this, nested divs serialized by JavaScript? Nested divs would also make it easy to allow reordering by the user, which is the end goal.
Does ASP.NET have a better way to handle this?
This feels hacky, but it works.
Using BeginCollectionItem, you can have the modal add hidden input elements to the DOM.
I wrote an action method that returns JSON with the modelstate (valid/invalid) and errors or partial HTML for invalid and valid submissions, respectively. Based on this, JavaScript either adds the errors to the summary or adds the requisite label and hidden inputs to the initial form.
Then have the main form's viewmodel contain an ICollection of your data model, called Contacts in below code, and ASP.NET handles the data binding with no troubles.
Example:
_CollectionItem.cshtml (partial HTML added to main form after valid submission)
#model Project.Models.ContactCreateViewModel
<li>
<div class="collection-item">
#using (Html.BeginCollectionItem("Contacts"))
{
<span class="item-name">#Model.LastName, #Model.FirstName</span> <span class="btn btn-danger delete-item">Delete</span>
#Html.HiddenFor(model => model.FirstName)
#Html.HiddenFor(model => model.LastName)
#Html.HiddenFor(model => model.PhoneNumber)
#Html.HiddenFor(model => model.PhoneExt)
#Html.HiddenFor(model => model.Email)
}
</div>
</li>
_CreateModal.cshtml (partial used for the body of the modal)
#model Project.Models.ContactCreateViewModel
<div class="modal-header">
<button type="button" class="close btn-modal-close" data-dismiss="modal"><i class="fas fa-times"></i></button>
<h4 class="modal-title">New Contact</h4>
</div>
<div class="modal-body">
#using (Html.BeginForm("CreateModal", "Contacts", FormMethod.Post, new { id = "new-contact-form" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummaryPlaceholder()
#* First Name *#
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
#* Last Name *#
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
#* Phone Number *#
<div class="form-group">
#Html.LabelFor(model => model.PhoneNumber, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { #class = "form-control phone" } })
#Html.ValidationMessageFor(model => model.PhoneNumber, "", new { #class = "text-danger" })
</div>
</div>
#* Phone Ext *#
<div class="form-group">
#Html.LabelFor(model => model.PhoneExt, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.PhoneExt, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PhoneExt, "", new { #class = "text-danger" })
</div>
</div>
#* Email *#
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
#* SUBMIT *#
<div class="form-group">
<div class="col-md-offset-4 col-md-8">
<input type="submit" value="Create" class="btn btn-success" />
</div>
</div>
</div>
}
</div>
#Scripts.Render("~/Scripts/Custom/ajax-add-collection-item.js")
<script>
$(function () {
ajaxAddCollectionItem("new-contact-form", "contacts", function () {
alertify.success("Added new contact");
})
});
</script>
ajax-add-collection-item.js (capture modal form submission, add _CollectionItem.cshtml to main form)
// Posts form and adds collection item to ul
function ajaxAddCollectionItem(formId, listId, onSuccess = function () { }) {
let $form = $("#" + formId);
$form.submit(function (event) {
event.preventDefault();
$.ajax({
method: "POST",
url: $form.attr("action"),
data: $form.serialize(),
success: function (data) {
let successful = data["success"];
// If form is valid, close modal and append new entry to list
if (successful) {
$("#" + listId).append(data["html"]);
$(".delete-item").click(function (event) {
$(this).closest("li").remove();
});
$(".btn-modal-close").trigger("click");
onSuccess();
}
// If form is not valid, display error messages
else {
displayValidationErrors(data["errors"]);
}
},
error: function (error) {
alert("Dynamic content load failed.");
console.error("Ajax call failed for form: " + $form);
}
});
});
// Populate validation summary
function displayValidationErrors(errors) {
let $ul = $('div.validation-summary-valid.text-danger > ul');
$ul.empty();
$.each(errors, function (i, errorMessage) {
$ul.append('<li>' + errorMessage + '</li>');
});
}
}
ContactsController.cs
public class ContactsController
{
// GET: Contacts/CreateModal
public ActionResult CreateModal()
{
return PartialView("_CreateModal");
}
// POST: Contacts/CreateModal
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> CreateModal(ContactCreateViewModel viewModel)
{
// If form is valid and email does not already exist, send HTML for collection item,
// otherwise send modelstate errors
if (ModelState.IsValid)
{
User user = await UserManager.FindByEmailAsync(viewModel.Email);
if (user == null)
// RenderPartialView returns partial HTML as a string,
// see https://weblog.west-wind.com/posts/2012/May/30/Rendering-ASPNET-MVC-Views-to-String
return Json(new { success = true, html = RenderPartialView("_CollectionItem", viewModel) });
else
ModelState.AddModelError("Email", "Email already exists.");
}
return Json(new { success = false, errors = GetModelStateErrors() });
}
// Actually in base controller class
protected string[] GetModelStateErrors()
{
return ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToArray();
}
}
I would like my Checkbox to disable EditorsFor if it is unchecked and enable them if it is checked. I know I have to use JavaScript, I found some codes in net, but it seems that they don't work.
Here is my View code:
#{Html.RenderPartial("_PartialError");}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
(...)
<div class="form-group">
#Html.LabelFor(model => model.Czy_zuzywalny, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Czy_zuzywalny)
#Html.ValidationMessageFor(model => model.Czy_zuzywalny, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Ilosc_minimalna, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Ilosc_minimalna, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Ilosc_minimalna, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Ilosc_optymalna, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Ilosc_optymalna, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Ilosc_optymalna, "", new { #class = "text-danger" })
</div>
</div>
(...)
}
And I wrote something like this and put in js file (ofc at the end of this code is ), but it doesn't work...
$(document).ready(function ()
{
$("#Czy_zuzywalny").click(function ()
{
if ($("#Ilosc_minimalna").attr("disabled") == "")
{
$("#Ilosc_minimalna").attr("disabled", "disabled");
$("#Ilosc_optymalna").attr("disabled", "disabled");
$("#Ilosc_minimalna").attr("value", "0");
$("#Ilosc_optymalna").attr("value", "0");
}
else
{
$("#Ilosc_minimalna").attr("disabled", "");
$("#Ilosc_optymalna").attr("disabled", "");
}
});
});
Nothing happens even if I check or uncheck my checkbox. Can anyone help me with that?
Change your jQuery code to:
$(document).ready(function () {
$("#Czy_zuzywalny").click(function () {
if ($("#Ilosc_minimalna").is('[disabled=disabled]')) {
$("#Ilosc_minimalna").removeAttr("disabled");
$("#Ilosc_optymalna").removeAttr("disabled");
}
else {
$("#Ilosc_minimalna").attr("disabled", "disabled");
$("#Ilosc_optymalna").attr("disabled", "disabled");
$("#Ilosc_minimalna").attr("value", "0");
$("#Ilosc_optymalna").attr("value", "0");
}
});
});
The if condition on your code never actually evaluates to true because in an enabled input, the 'disabled' attribute doesn't have a value of an empty string. it just doesn't exist (thus the use of removeAttr("disabled")).
UPDATE: Working JSFiddle here
UPDATE 2:
In order to add the script in the Create view and have it show after the jQuery script tag in the rendered HTML do this:
First add a call to RenderSection in your Layout file just before the closing </body> tag like this:
#RenderSection("scripts", required: false)
This will give you the ability to include a 'scripts' section in your views, the contents of which, will appear instead of the RenderSection call in the final HTML. Note that the required: false parameter specifies that you don't have to include this section in every view.
Then in your Create view, outside of any section add this:
#section scripts {
<script src="/scripts/CheckBoxItemCreate.js"></script>
}
Hope this helps!
My ASP.NET MVC 5 application's razor view uses two checkboxes:
<div class="form-group">
#Html.LabelFor(model => model.BoolField1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.BoolField1, new { htmlAttributes = new { #class = "form-control", #id = "bool1" } })
#Html.ValidationMessageFor(model => model.BoolField1, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BoolField2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.BoolField2, new { htmlAttributes = new { #class = "form-control", #id = "bool2" } })
#Html.ValidationMessageFor(model => model.BoolField2, "", new { #class = "text-danger" })
</div>
</div>
</div>
I'm trying implement the rule that BoolField2 cannot be true unless BoolField1 is also true. My jquery code:
function applyRule() {
var bool1Status = document.getElementById('bool1').checked;
var bool2Status = document.getElementById('bool2').checked;
if (bool2Status == true && bool1Status == false) {
// This is the sole error.
// Generate a suitable error message and display (how?)
}
}
The custom error generated at this code must be displayed into Html.ValidationMessageFor. How can I achieve this?
First you need to correct syntax for EditorFor () it should be like following
#Html.EditorFor(model => model.BoolField1, new { #class = "form-control", #id = "bool1" })
instead of
#Html.EditorFor(model => model.BoolField1, new { htmlAttributes = new { #class = "form-control", #id = "bool1" } })
Now after having this correction you may write custom jQuery logic to achieve same. Here is the code.
$(function () {
$('#bool2').on('click', function (e) {
//Get the state of 1st checkbox
var isFirstCheck = $('#bool1').is(":checked");
if (isFirstCheck==false) {
//dispay message if you need. Below line of code will prevent user to select 2nd checkbox
e.preventDefault();
}
})
});