Im using the following code which is created via MVC5 application and I've field called Type which is drop down list,what I need is that user and password box will be grayed out when you change to Prod currently by defult its Dev(the drop down list field - Type ) the user and passowrd field change to enabled ,how should I do that ?
public class Ad
{
public int ID { get; set; }
public string Name { get; set; }
public string User { get; set; }
public string Password { get; set; }
public IEnumerable<SelectListItem> Type
{
get
{
return new[]
{
new SelectListItem {Value = "D", Text = "Dev"},
new SelectListItem {Value = "p", Text = "Production"}
};
}
}
The create generated code
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Admin</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<
<div class="form-group">
#Html.LabelFor(model => model.User, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.User)
#Html.ValidationMessageFor(model => model.User)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Type, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Type, Model.Type)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
THe updated code with the script
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script type="text/javascript">
$('select[name="Type"]').change(function () {
if ($(this).val() === 'Production')
{
$('input[name="User"]').prop("disabled",true);
$('input[name="Password"]').prop("disabled",true);
}
else
{
$('input[name="User"]').prop("disabled",false);
$('input[name="Password"]').prop("disabled",false);
}
});
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Admin</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<
<div class="form-group">
#Html.LabelFor(model => model.User, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.User)
#Html.ValidationMessageFor(model => model.User)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Type, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Type, Model.Type)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
You need to do it using jquery like this:
<script type="text/javascript">
$(document).ready(function(){
$('select[name="Type"]').change(function(){
if($(this).val() === 'prod')
{
$('input[name="User"]').prop("disabled",true);
$('input[name="Password"]').prop("disabled",true);
}
else
{
$('input[name="User"]').prop("disabled",false);
$('input[name="Password"]').prop("disabled",false);
}
});
});
</script>
Here is Fiddle DEMO
You can use something like this:
$('#dropDownElement').change(function(){
if($(this).text() == "Production")
{
$('#passwordElement').prop('readonly',true);
$('#userElement').prop('readonly',true);
}
else
{
$('#passwordElement').prop('readonly',false);
$('#userElement').prop('readonly',false);
}
})
If prop('readonly',true); will not work, try attr('disabled', 'disabled');
Related
Goal: I'm trying to make a page that has the user enter in an address, then click a button that will verify it with a FedEx API. With the new verified address (now with the extra postal code from FedEx), I want to have the user verify that the new address is correct using a modal popup all without reloading the page.
Issue: I'm having a problem where the partial isn't showing and I'm not sure what I'm doing wrong.
Here's the View:
#model AirmotionEcommerceWebsite.Models.Home.DeliveryAddressModel
#{
ViewBag.Title = "Shipping Address";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<div class="container">
#Html.AntiForgeryToken()
<form class="form-horizontal">
<h4>Shipping Address</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<partial id="ValidateAddress"></partial>
<div class="form-group">
<h5>Name</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Attention To</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strAttnTo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strAttnTo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Street</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strStreet1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strStreet1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Street 2</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strStreet2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strStreet2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>City</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strCity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#{
IEnumerable<SelectListItem> dataItems = ViewBag.states;
}
<div class="form-group">
<h5>State</h5>
<div class="col-md-10">
#Html.DropDownListFor(model => model.State.IntStateId, dataItems, "-- Select --", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.State.IntStateId, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<h5>Zip</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strZip, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strZip, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" class="btn btn-primary" data-ajax-method="get" data-toggle="ajax-modal" data-target="#ValidateAddress"
data-url="#Url.Action("GetValidationOnAddress", new { model = Model })">
Verify Address
</button>
</div>
</div>
</form>
</div>
<script>
$(function () {
var PlaceHolderElement = $('#ValidateAddress');
$('button[data-toggle="ajax-modal"]').click(function (event) {
event.preventDefault();
var url = $(this).data('url');
// get the form containing the submit button
var form = $(this).closest('form')
// serialize all the fields in the form
var model = form.serialize();
// the the request to the url along with the form (model) data
$.get(url, model).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
$('#ValidateAddress').modal('show');
})
})
})
</script>
Here's the Controller:
[HttpGet]
public IActionResult GetValidationOnAddress(DeliveryAddressModel model)
{
FedexAPI fedexAPI = new FedexAPI();
List<string> listOfStreets = new List<string>();
listOfStreets.Add(model.strStreet1);
listOfStreets.Add(model.strStreet2);
var newAddress = fedexAPI.ValidateAddress(listOfStreets, model.strCity, model.State.StrStateCode, model.strZip, "US");
if (newAddress.customerMessages.Contains("INTERPOLATED.STREET.ADDRESS"))
{
// Address is not valid
model.ErrorMessage = "The address entered could not be found. Please double check your address. If issues perssist, please contact our office _________";
}
else
{
model.strStreet1 = newAddress.streetLinesToken[0];
if (newAddress.streetLinesToken.Count > 1)
model.strStreet2 = newAddress.streetLinesToken[1];
model.strCity = newAddress.city;
model.strZip = newAddress.postalCode;
}
return PartialView("_AddressValidationPartial", model);
}
And lastly here's the Partial View:
#model AirmotionEcommerceWebsite.Models.Home.DeliveryAddressModel
<div class="modal fade" id="ValidateAddress">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="ValidateAddressLabel">Validate Address</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="Create">
<div class="form-group">
#if (Model.ErrorMessage == null)
{
<h5>#Model.strName</h5>
#if (Model.strAttnTo != null)
{<h5>#Model.strAttnTo</h5>}
<h5>#Model.strStreet1</h5>
#if (Model.strStreet2 != null)
{<h5>#Model.strStreet2</h5>}
<h5>#Model.strCity</h5>
<h5>#Model.State.StrStateCode</h5>
<h5>#Model.strZip</h5>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Accept Changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Edit</button>
</div>
}
else
{
<h4>#Model.ErrorMessage</h4>
}
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-save="modal">Save Changes</button>
</div>
</div>
</div>
</div>
I checked the console and found it was not able to find my partial view. Quick file move and it's working now! Thanks to #viveknuna for helping me notice this!
I have a form, I would like where I have Html.TextBoxFor into labels is this possible?
#* title *#
<div class="form-group">
<label class="control-label col-md-4">Song Title</label>
<div class="col-md-4">
#foreach (var t in Model.OriginalWork.AlternativeTitles)
{<label class="control-label text-muted">#t.Title</label>
}
</div>
</div>
#* Alternative Titles *#
<div class="form-group">
#Html.LabelFor(m => m.OriginalWork.AlternativeTitles, new { #class = "control-label col-md-4" })
<div class="col-md-8">
<div class="row">
<div class="tag-container tags col-md-12" data-bind="foreach: AlternateTitles">
#foreach (var t in Model.OriginalWork.AlternativeTitles)
{<span class="tm-tag tm-tag-info" data-bind="hidden: IsDeleted">
#t.Title
</span>
}
</div>
</div>
</div>
</div>
#* Duration *#
<div class="form-group mbn">
<label class="control-label col-md-4 pull-left hidden-sm" for="DurationMinutes">Duration</label>
<div class="col-md-1 mb15">
#Html.LabelFor(m => m.OriginalWork.DurationMins, new { #class = "control-label pull-left hidden-md hidden-lg hidden-xl" })
#Html.TextBoxFor(m => m.OriginalWork.DurationMins, new { #class = "form-control isDisabled", placeholder = "Mins...", data_bind = "value: DurationMins" })
#Html.ValidationMessageFor(m => m.OriginalWork.DurationMins, string.Empty, new { #class = "text-danger" })
</div>
<div class="col-md-1 mb15">
#Html.LabelFor(m => m.OriginalWork.DurationSecs, new { #class = "control-label pull-left hidden-md hidden-lg hidden-xl" })
#Html.TextBoxFor(m => m.OriginalWork.DurationSecs, new { #class = "form-control isDisabled", placeholder = "Secs...", data_bind = "value: DurationSecs" })
#Html.ValidationMessageFor(m => m.OriginalWork.DurationSecs, string.Empty, new { #class = "text-danger" })
</div>
</div>
#* Performing Artists *#
<div class="form-group">
#Html.LabelFor(m => m.OriginalWork.PerformingArtistNames, new { #class = "control-label col-md-4" })
<div class="col-md-8">
<div class="row">
<div class="tag-container tags col-md-12" data-bind="foreach: PerformingArtistNames">
#foreach (var t in Model.OriginalWork.PerformingArtistNames)
{<span class="tm-tag tm-tag-info" data-bind="hidden: IsDeleted">
#t.Firstname #t.Lastname
</span>
}
</div>
</div>
</div>
</div>
#* remix and samples *#
<div class="form-group">
#Html.LabelFor(m => m.OriginalWork.IsRemix, new { #class = "control-label col-md-4" })
<div class="col-md-8">
<div class="admin-form theme-primary">
<div class="radio-custom radio-primary mt10 mr10 pull-left">
#Html.RadioButtonFor(m => m.OriginalWork.IsRemix, true, new { #class = "control-label col-md-4" })
<label for="IsRemixYes">Yes</label>
</div>
<div class="radio-custom radio-primary mt10 pull-left">
#Html.RadioButtonFor(m => m.OriginalWork.IsRemix, false, new { #class = "control-label col-md-4" })
<label for="IsRemixNo">No</label>
</div>
</div>
</div>
</div>
#*Contains Sample Radio Button*#
<div class="form-group">
#Html.LabelFor(m => m.OriginalWork.ContainsSample, new { #class = "control-label col-md-4" })
<div class="col-md-8">
<div class="admin-form theme-primary">
<div class="radio-custom radio-primary mt10 mr10 pull-left">
#Html.RadioButtonFor(m => m.OriginalWork.ContainsSample, true, new { #class = "control-label col-md-4" })
<label for="ContainsSampleYes">Yes</label>
</div>
<div class="radio-custom radio-primary mt10 pull-left">
#Html.RadioButtonFor(m => m.OriginalWork.ContainsSample, false, new { #class = "control-label col-md-4" })
<label for="ContainsSampleNo">No</label>
</div>
</div>
</div>
</div>
#* ISWC *#
<div class="form-group">
#Html.LabelFor(m => m.OriginalWork.Iswc, new { #class = "control-label col-md-4" })
<div class="col-md-4">
#Html.TextBoxFor(m => m.OriginalWork.Iswc, new { #class = "form-control isDisabled", placeholder = "ISWC", data_bind = "value: Iswc" })
#Html.ValidationMessageFor(m => m.OriginalWork.Iswc, string.Empty, new { #class = "text-danger" })
</div>
</div>
</div>
</fieldset>
If you want to disable your radio button, assuming you're using razor syntax, you can use:
#Html.RadioButtonFor(m => m.SomeModelItem, "false")
And this should put you on the right track.
I want to export my Viewmodel from my view to my controller which is receiving it in a method, this is my view:
#using Resources
#model MyProject.ViewModel.CertificationViewModel
#{
ViewBag.Title = Resources.titleCertificationList;
#section css
{
<link href="#Url.Content("~/layout/css/stylesformador.css")" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
}
}
<div class="mainblock">
<div class="block-group">
<div class="ttitle title">#HIQResources.titleEdit</div>
</div>
#using (Html.BeginForm("Edit", "Certification", FormMethod.Post, new { id = "form1" }))
{
#Html.AntiForgeryToken()
<div class="md-content">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.pdf, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#*<input type="file" name="file" />*#
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control inputForm", #type="file" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Code, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Code, new { htmlAttributes = new { #class = "form-control inputForm", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.Code, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SelectedEntityId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.SelectedEntityId, Model.EntitiesDrop, htmlAttributes: new { #class = "form-control inputForm" })
#Html.HiddenFor(model => model.SelectedEntityId)
#Html.ValidationMessageFor(model => model.SelectedEntityId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StatusId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.StatusId, Model.StatusDrop, htmlAttributes: new { #class = "form-control inputForm" })
#Html.HiddenFor(model => model.StatusId)
#Html.ValidationMessageFor(model => model.StatusId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Result, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Result, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Result, "", new { #class = "text-danger"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Observation, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Observation, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Observation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1">
<div class="col-md-8">
<table class="table table-bordered">
<tr>
<th class="col-md-2">
#Html.DisplayNameFor(model => model.FileName)
</th>
<th class="col-md-2">Ficheiro</th>
</tr>
#foreach (var item in Model.teste)
{
<tr>
<td>
#if (item.FileName == null)
{
<h5>Não existem ficheiros para esta certificação.</h5>
}
else
{
#Html.DisplayFor(modelItem => item.FileName)
}
</td>
<td>
#if (item.FileName == null)
{
<h5>Não existem ficheiros para esta certificação.</h5>
}
else
{
Download
#*Delete*#
<input type="submit" value="Edit" id="Delete" class="btn btn-default btn-sm btn-detail" />
}
#*#Html.ActionLink("Download", "Certification", "Download", new { id = Model.Id })*#
</td>
</tr>
}
</table>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-8">
<input type="submit" value="#HIQResources.buttonSave" class="btn btn-default btn-sm btn-detail" />
#Html.ActionLink(HIQResources.buttonBack, "CertificationList", new { id = Model.StudentId, nome = Model.StudentName }, new { #class = "btn btn-default btn-sm btn-edit" })
</div>
</div>
</div>
</div>
}
</div>
#section Scripts {
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/HIQTrainingScripts/Certification/Edit.js"></script>
<script>
$("#Date").datepicker({ dateFormat: 'yy/mm/dd' });
$("#Delete").click(function () {
var vm = $('#Model').serialize();
alert(vm)
var token = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
url: "/Certification/Edit",
type: "POST",
data: {
__RequestVerificationToken: token,
vm: vm,
click: "deu",
},
sucess: function (result) {
alert("sucess");
}
});
});
</script>
}
This is the method in my controller:
[Authorize(Roles = "Admin, Staff")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CertificationViewModel vm, string click) {
if (click == "deu")
{
int lol = _servicesFactory.GetService<ICertificationManager>().DeleteFile(vm, GetLoggedUser());
return View(vm);
}
}
The value of my ViewModel comes always as null to my Jquery variable and I don't know why, because it should come with the info from the view to the controller in order for me, to execute my task.
Am I missing something ?
#model CommonLayer.ORDER
#{
ViewBag.Title = "Update";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h4>Update Order Status</h4>
<br />
#if (Model.OrderStatus != "Shipped")
{
using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.UserId)
<div class="form-group">
#Html.LabelFor(model => model.OrderId, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderId, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderStatus, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
<select class="form-control" name="OrderStatus">
<option value="Pending" id="pending">Pending</option>
<option value="Shipped" id="shipped">Shipped</option>
</select>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderDate, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderDate, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderNumber, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderNumber, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<form action="/order/update/#Model.OrderId" method="post" enctype="multipart/form-data">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn btn-primary" />
</div>
</div>
</form>
</div>
}
}
else
{
<h4>Order Has Been Shipped!</h4>
}
My submit button isn't working regardless of the correct syntax being used. When I press the button nothing happens, as if I haven't clicked it, no redirecting whatsoever.
Was working until yesterday. Did not change any code whatsoever regarding the form or corresponding controller.
This is the controller corresponding to the form.
[HttpGet]
[Authorize(Roles = "ADM")]
public ActionResult Update(Guid Id)
{
BusinessLayer.Orders order = new BusinessLayer.Orders();
return View(order.GetOrder(Id));
}
[HttpPost]
[Authorize(Roles = "ADM")]
public ActionResult Update(CommonLayer.ORDER order, Guid id)
{
BusinessLayer.Orders blorder = new BusinessLayer.Orders();
blorder.UpdateOrder(order);
return RedirectToAction("UpdateDetails", new {id=id});
}
Use below code, let us know if doesn't work
Added below line to pass the orderid
#Html.HiddenFor(model => model.OrderId)
Updated below line to call action of a controller
Html.BeginForm("update","order",FormMethod.Post)
Finally removed the unnecessary form tag
Removed antiforgerytoken from view as you are not checking in you action method.
If you want to add that then you need to add [ValidateAntiForgeryToken] after [httppost] of Update Action method
#model CommonLayer.ORDER
#{
ViewBag.Title = "Update";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h4>Update Order Status</h4>
<br />
#if (Model.OrderStatus != "Shipped")
{
using (Html.BeginForm("Update","Order",FormMethod.Post))
{
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.UserId)
#Html.HiddenFor(model => model.OrderId)
<div class="form-group">
#Html.LabelFor(model => model.OrderId, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderId, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderStatus, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
<select class="form-control" name="OrderStatus">
<option value="Pending" id="pending">Pending</option>
<option value="Shipped" id="shipped">Shipped</option>
</select>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderDate, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderDate, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderNumber, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderNumber, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn btn-primary" />
</div>
</div>
</div>
}
}
else
{
<h4>Order Has Been Shipped!</h4>
}
I am trying to upload image files from my form along with other fields in my model. My HttpPostedFileBase collection is always empty and the count is 0.
I have referred many other questions relating to this in SO but somehow I am unable to find the solution.
View:
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Id, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Id)
#Html.ValidationMessageFor(model => model.Id)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProfileId, "ProfileId", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ProfileId", String.Empty)
#Html.ValidationMessageFor(model => model.ProfileId)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image1, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="fileuploadImage1" type="file" />
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image2, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="fileuploadImage2" type="file" />
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image3, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="fileuploadImage3" type="file" />
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image4, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="fileuploadImage4" type="file" />
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image5, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="fileuploadImage5" type="file" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,ProfileId,fileuploadImage1,fileuploadImage2,fileuploadImage3,fileuploadImage4,fileuploadImage5,Files")] HomepageSetting homepagesetting)
{
if (ModelState.IsValid)
{
try
{
List<String> imagesFilenames = new List<String>();
/*Lopp for multiple files*/
foreach (HttpPostedFileBase file in homepagesetting.Files)
{
/*Geting the file name*/
string filename = System.IO.Path.GetFileName(file.FileName);
/*Saving the file in server folder*/
file.SaveAs(Server.MapPath("~/Images/" + filename));
string filepathtosave = "Images/" + filename;
imagesFilenames.Add(filepathtosave);
}
if(imagesFilenames.Count == 1)
{
homepagesetting.Image1 = imagesFilenames[0];
}
else if (imagesFilenames.Count == 2)
{
homepagesetting.Image1 = imagesFilenames[0];
homepagesetting.Image2 = imagesFilenames[1];
}
else if (imagesFilenames.Count == 3)
{
homepagesetting.Image1 = imagesFilenames[0];
homepagesetting.Image2 = imagesFilenames[1];
homepagesetting.Image3 = imagesFilenames[2];
}
else if (imagesFilenames.Count == 4)
{
homepagesetting.Image1 = imagesFilenames[0];
homepagesetting.Image2 = imagesFilenames[1];
homepagesetting.Image3 = imagesFilenames[2];
homepagesetting.Image4 = imagesFilenames[3];
}
else if (imagesFilenames.Count == 5)
{
homepagesetting.Image1 = imagesFilenames[0];
homepagesetting.Image2 = imagesFilenames[1];
homepagesetting.Image3 = imagesFilenames[2];
homepagesetting.Image4 = imagesFilenames[3];
homepagesetting.Image5 = imagesFilenames[4];
}
ViewBag.Message = "File Uploaded successfully.";
}
catch
{
ViewBag.Message = "Error while uploading the files.";
}
db.HomepageSettings.Add(homepagesetting);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ProfileId = new SelectList(db.Profiles, "Id", "name", homepagesetting.ProfileId);
return View(homepagesetting);
}
Model:
public partial class HomepageSetting
{
public int Id { get; set; }
//other model properties
public string Image1 { get; set; }
public string Image2 { get; set; }
public string Image3 { get; set; }
public string Image4 { get; set; }
public string Image5 { get; set; }
public virtual Profile Profile { get; set; }
public List<HttpPostedFileBase> Files { get; set; }
public HomepageSetting()
{
Files = new List<HttpPostedFileBase>();
}
}
Can any one point me to what I am doing wrong here?
Instead of foreach loop do it this way, it happens with foreach as i also faced this issue:
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase myFile = Request.Files[i];
}
In MVC you always have to proper name of html element in order to work its default binding. In your case
fileupload control has name like fileuploadImage1 , fileuploadImage2 and that not present in your model so it is not binding.
I suggest that you should name all your file upload element name.
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Id, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Id)
#Html.ValidationMessageFor(model => model.Id)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProfileId, "ProfileId", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ProfileId", String.Empty)
#Html.ValidationMessageFor(model => model.ProfileId)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image1, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="files" type="file" />
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image2, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="files" type="file" />
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image3, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="files" type="file" />
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image4, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="files" type="file" />
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image5, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="files" type="file" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Your action you have to do .
[HttpPost]
public ActionResult View1([Bind(Include = "Id,ProfileId,fileuploadImage1,fileuploadImage2,fileuploadImage3,fileuploadImage4,fileuploadImage5,Files")] HomepageSetting homepagesetting)
{
for (int i = 0; i < homepagesetting.Files.Count; i++)
{
if (homepagesetting.Files[i] != null)
{
}
}
return View();
}