How to use SweetAlert before return RedirectToAction by Form Post? - asp.net-mvc

Model
public class Company{
[StringLength(30)]
public string Name{ get; set; }
[StringLength(15)]
public string RegisterNo { get; set; }
}
View
<form id="form" method="post" action="/Controller/Save" style="font-size:13px;">
<div class="row pb-3">
<div class="form-row">
<div class="col-md-3">
<div class="position-relative form-group">
<label class="">Company Name</label> #Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control", #maxlength = "30" } })
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-6">
<div class="position-relative form-group">
<label class="">Reg No</label> #Html.EditorFor(model => model.RegisterNo, new { htmlAttributes = new { #class = "form-control", #maxlength = "15" } })
</div>
</div>
</div>
</div>
</form>
<button name="submit">Save</button>
Controller
public ActionResult Save(Company CompDet){
string Name = CompDet.Name;
string RegNo = CompDet.RegisterNo;
//then Connect DB and Save DB
//HOW TO use SweetAlert before, return RedirectToAction
}
I'm currently using, return RedirectToAction Only.
How to add SweetAlert before RedirectToAction?
Using Ajax Post or Form Post?
Possible that using Ajax & Form Post Together?
After Saving -> Show Sweetalert success -> return redirectToAction
I'm still at the learning level. Please Help.
Thank You

Related

How to find an item in my database?

So i want to create a person and add it to my table if i dont have the same name already in my table. i have this code in my controller
hesaplamaEntities hsb = new hesaplamaEntities();
[HttpPost]
public ActionResult Create(MyTable p)
{
MyTable obj = hsb.MyTable.Find(p);
if (obj.propname == null)
{
hsb.MyTable.Add(p);
hsb.SaveChanges();
return RedirectToAction("Create", "Home");
}
else
{
return HttpNotFound();
}
and this is my View :
#using (Html.BeginForm("Create", "Home", FormMethod.Post, new { #class =
"form-horizontal", enctype = "multipart/form-data" }))
{
<div class="row">
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-12">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
#Html.TextBoxFor(m => m.propname, new { #class = "form-control" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="col-sm-2 control-label">kod</label>
<div class="col-sm-10">
#Html.TextAreaFor(m => m.propkod, new { #class = "form-control" })
</div>
</div>
</div>
</div>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-sm-9 col-sm-offset-3">
<div class="btn-toolbar pull-right">
<input type="submit" value="save" class="btn btn-primary" />
</div>
</div>
</div>
</div>
}
and this is my Model :
public partial class MyTable
{
public int ID { get; set; }
public string propkod { get; set; }
public string propname { get; set; }
}
i am having this error when i am trying to add person :
he specified parameter type 'WebApplication7.Models.MyTable' is not valid. Only scalar types, such as System.Int32, System.Decimal, System.DateTime, and System.Guid, are supported.
and its showing me the error in this line : HesapTemel obj = hsb.HesapTemels.Find(p);
what is the probleme exactly ?

ASP.NET MVC Multiple form in one page: Validation doesn't work [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am creating a register login page in asp mvc and as i need, this page has two models and two form actions.
every thing is ok but the validation.
the models are:
public class Account_Index_ViewModel
{
public UserAccount_Login_ViewModel userAccount_Login_ViewModel { get; set; }
public UserAccount_Register_ViewModel userAccount_Register_ViewModel { get; set; }
}
public class UserAccount_Login_ViewModel
{
[Required]
[DataType(DataType.Password)]
public string Pass { get; set; }
[Required]
public string LoginName { get; set; } // NickName/Email/MobilePhone
}
public class UserAccount_Register_ViewModel
{
public string NickName { get; set; }
public string Passw { get; set; }
public string PassConfirm { get; set; }
public string Email { get; set; }
public string MobilePhone { get; set; }
}
and the view :
#model GhafasehWebSite.Models.Account_Index_ViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div class="AccountBook">
<div class="half-width">
#using (Html.BeginForm("Login", "Account"))
{
Html.EnableClientValidation();
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ورود به سیستم</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group col-md-12">
#Html.LabelFor(model => ((GhafasehWebAPI.Models.UserAccount_Login_ViewModel)(model.userAccount_Login_ViewModel)).LoginName, new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.TextBoxFor(model => ((GhafasehWebAPI.Models.UserAccount_Login_ViewModel)(model.userAccount_Login_ViewModel)).LoginName, new { #class = "form-control", placeholder = "نام مستعار/ایمیل/شماره موبایل" })
#Html.ValidationMessageFor(model => ((GhafasehWebAPI.Models.UserAccount_Login_ViewModel)(model.userAccount_Login_ViewModel)).LoginName)
</div>
</div>
<div class="form-group col-md-12">
#Html.LabelFor(model => ((GhafasehWebAPI.Models.UserAccount_Login_ViewModel)(model.userAccount_Login_ViewModel)).Pass, new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.TextBoxFor(model => ((GhafasehWebAPI.Models.UserAccount_Login_ViewModel)(model.userAccount_Login_ViewModel)).Pass, new { #class = "form-control" })
#Html.ValidationMessageFor(model => ((GhafasehWebAPI.Models.UserAccount_Login_ViewModel)(model.userAccount_Login_ViewModel)).Pass)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-10">
<input type="submit" value="ورود" class="btn btn-primary" />
</div>
</div>
</div>
}
</div>
<div class="half-width">
#using (Html.BeginForm("Register","Account"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ثبت نام در سیستم</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group col-md-12">
#Html.LabelFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).NickName, new { #class = "control-label col-md-4" })
<div class=" col-md-8">
#Html.TextBoxFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).NickName, new { #class = "form-control" })
#Html.ValidationMessageFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).NickName)
</div>
</div>
<div class="form-group col-md-12">
#Html.LabelFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).Passw, new { #class = "control-label col-md-4" })
<div class=" col-md-8">
#Html.TextBoxFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).Passw, new { #class = "form-control" })
#Html.ValidationMessageFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).Passw)
</div>
</div>
<div class="form-group col-md-12">
#Html.LabelFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).PassConfirm, new { #class = "control-label col-md-4" })
<div class=" col-md-8">
#Html.TextBoxFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).PassConfirm, new { #class = "form-control" })
#Html.ValidationMessageFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).PassConfirm)
</div>
</div>
<div class="form-group col-md-12">
#Html.LabelFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).Email, new { #class = "control-label col-md-4" })
<div class=" col-md-8">
#Html.TextBoxFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).Email, new { #class = "form-control" })
#Html.ValidationMessageFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).Email)
</div>
</div>
<div class="form-group col-md-12">
#Html.LabelFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).MobilePhone, new { #class = "control-label col-md-4" })
<div class=" col-md-8">
#Html.TextBoxFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).MobilePhone, new { #class = "form-control" })
#Html.ValidationMessageFor(model => ((GhafasehWebAPI.Models.UserAccount_Register_ViewModel)model.userAccount_Register_ViewModel).MobilePhone)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-10">
<input type="submit" value="ثبت نام" class="btn btn-success" />
</div>
</div>
</div>
}
</div>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
and the controller:
[HttpGet]
public ActionResult Index()
{
return View(new Account_Index_ViewModel());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserAccount_Login_ViewModel model)
{
if (ModelState.IsValid)
{
if (DataProvider.LoginUser(model, ModelState, Request, Session))
{
return RedirectToAction("Index", "Home");
}
}
return View("Index");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(UserAccount_Register_ViewModel model)
{
if (ModelState.IsValid)
{
if (DataProvider.RegisterUser(model, ModelState, Request, Session))
{
return RedirectToAction("Index", "Home");
}
}
return View("Index");
}
you should know that server side validation works fine but the client side is asleep.
So, what do you suggest?
When you say the validation doesn't work what do you mean? you press Login button with empty username/password and it doesn't show required error?
If so , I Created new project with your model view controller and it worked !!! The validation works.

What is the preferred way to standardise complex html views for data types?

I have code like this that I repeat through many MVC editing views. This example is the default way we display a checkbox, but similar repetition is found with other input types.
<div class="form-group">
#Html.LabelFor(model => model.IsLive, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-8 checkbox">
<div class="col-xs-1">
#Html.EditorFor(model => model.IsLive)
</div>
<div class="col-xs-10">
#Html.CheckboxLabelFor(model => model.IsLive)
</div>
</div>
<a class="infoonclick col-md-1" title="#Html.DisplayNameFor(model => model.IsLive)" data-content="#Html.DescriptionFor(model => model.IsLive)">
<span class="fa fa-info-circle"></span>
</a>
</div>
I am wondering what is the best way to DRY and standardise this?
I want to do something like #Html.DefaultCheckboxEditorFor(model => model.IsLive)
I tried creating a custom HtmlHelper, but this seemed to involve too many hard coded strings to be a good idea.
Rather I feel I should be using EditorTemplates for this, but I can't quite get the syntax right. The model for the view is a bool, but I need to get property specific stuff like the display name and descriptions.
#model bool
<div class="form-group">
#Html.LabelFor(model => model.IsLive, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-8 checkbox">
<div class="col-xs-1">
#Html.EditorFor(model => model.IsLive)
</div>
<div class="col-xs-10">
#Html.CheckboxLabelFor(model => model.IsLive)
</div>
</div>
<a class="infoonclick col-md-1" title="#Html.DisplayNameFor(model => model.IsLive)" data-content="#Html.DescriptionFor(model => model.IsLive)">
<span class="fa fa-info-circle"></span>
</a>
</div>
I have a project where most of my views look like:
(This also works with multi-level deep complex objects, but not with any type of collection, like IEnumerable, although it could be modified to do so)
<h3>Edit existing page</h3>
<div class="col-xs-12">
#using (Html.BeginForm("Edit", "Page", FormMethod.Post, new { role = "role" }))
{
#Html.EditorForModel()
<input type="submit" value="Save" class="btn btn-primary" />
}
</div>
I think that's pretty cool. So the model looks like:
public class PageEditViewModel
{
[Editable(false)]
[DisplayName("Page Id")]
public Guid Id { get; set; }
[Editable(false)]
[DisplayName("Url to resource (format: '/my-resource' or '/sub/resource)'")]
public string Url { get; set; }
[Required]
[MaxLength(50, ErrorMessage = "Maximum Length of 50 Exceeded.")]
[DisplayName("Title for page (must match Url ex: 'My Resource' or 'Sub Resource'")]
public string PageTitle { get; set; }
[MaxLength(int.MaxValue, ErrorMessage = "Content Exceeded Maximum Length")]
[DataType(DataType.MultilineText)]
public string Content { get; set; }
}
I have some editor templates:
\Views\Shared\EditorTemplates\multilinetext.cshtml
#model object
#{
var htmlAttributes = this.ViewData.ModelMetadata.GetHtmlAttributes();
}
<div class="form-group #Html.ErrorClassFor(m => m, "has-error")">
#Html.LabelFor(m => m, new { #class = "control-label" })
<div class="controls">
#Html.TextAreaFor(
m => m,
8, 8,
htmlAttributes)
#Html.ValidationMessageFor(m => m, null, new { #class = "help-block" })
</div>
</div>
And it all magically works with the a modified version of object.cshtml:
#model object
#using System.Text;
#using System.Data;
#{
ViewDataDictionary viewData = Html.ViewContext.ViewData;
TemplateInfo templateInfo = viewData.TemplateInfo;
ModelMetadata modelMetadata = viewData.ModelMetadata;
System.Text.StringBuilder builder = new StringBuilder();
string result;
// DDB #224751
if (templateInfo.TemplateDepth > 2)
{
result = modelMetadata.Model == null ? modelMetadata.NullDisplayText
: modelMetadata.SimpleDisplayText;
}
foreach (var prop in modelMetadata.Properties.Where(pm =>
pm.ShowForEdit
//&& pm.ModelType != typeof(System.Data.EntityState)
&& !templateInfo.Visited(pm)
)
.OrderBy(pm => pm.Order))
{
//Type modelType = Model.GetType();
Type modelType = modelMetadata.ModelType;
System.Reflection.PropertyInfo pi = modelType.GetProperty(prop.PropertyName);
System.ComponentModel.DataAnnotations.DisplayAttribute attribute = pi.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute), false).FirstOrDefault() as System.ComponentModel.DataAnnotations.DisplayAttribute;
if (attribute != null
&& !string.IsNullOrWhiteSpace(attribute.GetGroupName()))
{
//builder.Append(string.Format("<div>{0}</div>", attribute.GetGroupName()));
builder.Append(Html.Partial("Partial-GroupName", attribute.GetGroupName()));
}
builder.Append(Html.Editor(prop.PropertyName, prop.TemplateHint ?? prop.DataTypeName).ToHtmlString());
}
result = builder.ToString();
}
#Html.Raw(result)
Example output:
My EditFor templates are versions of MacawNL BootstrapEditorTemplates (which I have no affiliation with).

Field required attribute acidentially invoked but clicking a button

I have these fields, and I implemented required attribute on them.
#using (Html.BeginForm("Edit", "ChannelsGrid", FormMethod.Post, new {name = "channelForm", #class = "channelForm", #enctype = "multipart/form-data"}))
{
<div class="form-group">
#Html.HiddenFor(model => Model.Id)
<div class="row">
<div class="col-md-6">
#Html.Label("Part/Location", new {#class = "control-label"})
#Html.TextBox("PartLocation", null, new { #class = "form-control", #required = "required" })
</div>
<div class="col-md-6">
#Html.Label("Index", new {#class = "control-label"})
#Html.TextBox("Index", null, new {#class = "form-control"})
</div>
</div>
<div class="row">
<div class="col-md-6">
#Html.Label("Measurement", new {#class = "control-label"})
#Html.DropDownListFor(model => model.Measurement, (SelectList)ViewBag.Measurements, "-- Select Measurement --", new { #class = "form-control", #required = "required" })
</div>
<div class="col-md-6">
#Html.Label("Location", new {#class = "control-label"})
#Html.DropDownList("Directions", ViewBag.DirectionTypes as List<SelectListItem>, "-- Select Direction --", new { #class = "form-control", #required = "required" })
</div>
</div>
<div class="row">
<div class="col-md-6">
#Html.LabelFor(model => model.ChannelGroupId, new {#class = "control-label"})
#Html.DropDownListFor(x => x.ChannelGroupId, Model.ChannelGroups, "Select Channel Group", new {#class = "form-control"})
#Html.ValidationMessageFor(model => model.ChannelGroupId)
</div>
<div class="col-md-3">
<label class="control-label"></label>
<a href="#" id="addChannelGroup" class="form-control" style="border: none">
<i class="fa fa-plus-circle">Add Group</i>
</a>
</div>
<div class="col-md-3">
<label class="control-label"></label>
<a href="#" id="addMeasurement" class="form-control" style="border: none">
<i class="fa fa-plus-circle">Add Measurement</i>
</a>
</div>
</div>
<br/>
<div class="row">
<div class="col-md-6">
#Html.Label("Channel name: ", new {id = "channelName", #class = "control-label"})
</div>
<div class="col-md-6">
#Html.TextBox("HiddenTextBox", null, new {#class = "hidden"})
<div class="col-md-1">
#Html.TextBoxFor(a => a.Name, new {#class = "hidden"})
</div>
</div>
</div>
</div>
<div class="row" id="pnlAddChannelGroupName" style="display: none">
<div class="col-md-6">
<label class="control-label">Channel Group Name :</label>
<input type="text" id="ChannelGroupName" name="ChannelGroupName" class="form-control"/>
<input type="button" value="Cancel" id="channelGroupButton" />
#*<button id="channelGroupButton">Cancel</button>*#
</div>
</div>
<div class="row" id="pnlMeasurement" style="display: none">
<div class="col-md-6">
#Html.Label("Measurement :", new {#class = "control-label"})
#Html.TextBox("MeasurementName", null, new {#class = "form-control"})
<input type="button" value="Cancel" id="measurementButton" />
#*<button id="measurementButton">Cancel</button>*#
</div>
</div>
}
I also have two buttons which are used to toggle other textboxes in this form. Here is the code.
<div class="row" id="pnlAddChannelGroupName" style="display: none">
<div class="col-md-6">
<label class="control-label">Channel Group Name :</label>
<input type="text" id="ChannelGroupName" name="ChannelGroupName" class="form-control"/>
<button id="channelGroupButton">Cancel</button>
</div>
</div>
<div class="row" id="pnlMeasurement" style="display: none">
<div class="col-md-6">
#Html.Label("Measurement :", new {#class = "control-label"})
#Html.TextBox("MeasurementName", null, new {#class = "form-control"})
<button id="measurementButton">Cancel</button>
</div>
</div>
The problem is whenever I click these two Cancel buttons in that field, the three fields seems to be invoked and there is brown border around the textbox dropdownlist. I guess these field have been submitted. But I thought I use button element instead of type button of an input so I can eliminate the submitting action of the button, right? Any clues? And how can I click these Cancel buttons withouts invoking validation in these other field?
Edited: I changed all the buttons to input type="button" and the validation of these other field dissapeared. Can someone explain?
This is my viewmodel:
namespace CrashTestScheduler.Entity.ViewModel
{
public class ChannelViewModel
{
public int Id { get; set; }
//[Display(Name = "Name")]
//[Required(ErrorMessage = "Please specify the channel name.")]
public string Name { get; set; }
public string Description { get; set; }
public string ChannelGroupName { get; set; }
public string MeasurementName { get; set; }
[Required(ErrorMessage = "Please select a channel group.")]
public int ChannelGroupId { get; set; }
public IEnumerable<SelectListItem> ChannelGroups { get; set; }
//[Required]
public string Measurement { get; set; }
}
}
The reason your form is submitting when clicking buttons is that the default action for a <button> element is type="submit" (refer documentation). You need to explicitly set the type attribute
<button type="button" ....>
However you have numerous issues with your approach.
By removing the [Required] attributes and using the required =
"required" html attribute, you now need to include manual
validation on the controller (never trust the user!)
Your mixing up Razor and manual html in the view, potentially
creating problems for model binding. Some of your label elements
wont work. (e.g. the first one is associated with a control named
"Part/Location" but there is no control named "Part/Location").
The user interface where your force users to click buttons to swap
between textboxes and dropdown lists is confusing and a sure way to
lose customers. Instead you should use an autocomplete control such
as jQuery Autocomplete which allows selection from a list or
direct text entry.
Your view model should contain validation attributes for its properties and can be simplified to
public class ChannelViewModel
{
public int Id { get; set; }
[Display(Name = "Part/Location")]
[Required]
public string PartLocation { get; set; }
public string Index { get; set; }
[Required]
public string Measurement { get; set; }
[Required]
[Display(Name = "Location")]
public int Direction { get; set; }
.... // other properties
public SelectList DirectionList { get; set; }
}
View
#Html.HiddenFor(model => Model.Id)
#Html.LabelFor(m => m.PartLocation, new {#class = "control-label"})
#Html.TextBoxFor(m => m.PartLocation, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.PartLocation)
#Html.LabelFor(m => m.Index, new {#class = "control-label"})
#Html.TextBoxFor(m => m.Index, new {#class = "form-control"})
#Html.LabelFor(m => m.Measurement, new {#class = "control-label"})
#Html.TextBoxFor(m => m.Measurement, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Measurement)
#Html.LabelFor(m => m.Direction, new {#class = "control-label"})
#Html.DropDownListFor(m => m.Direction, Model.DirectionList, "-- Select Direction --", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Direction)
.... // more controls
The attach the autocomplete to $(#Measurement).autocomplete({...
This will give you client and server side validation out of the box, and a better user interface.

HttpPostedFileBase not binding to model

here is my ViewModel
public class FaultTypeViewModel
{
[HiddenInput(DisplayValue = false)]
public int TypeID { get; set; }
[Required(ErrorMessageResourceType = typeof(AdministrationStrings), ErrorMessageResourceName = "FaultTypeNameRequired")]
[Display(ResourceType = typeof(AdministrationStrings), Name = "FaultTypeName")]
public string TypeName { get; set; }
[Display(ResourceType = typeof(AdministrationStrings), Name = "FaultTypeDescription")]
[DataType(DataType.MultilineText)]
public string TypeDescription { get; set; }
[Display(ResourceType = typeof(AdministrationStrings), Name = "FaultTypeImageFile")]
public HttpPostedFileBase TypeImageFile { get; set; }
[HiddenInput(DisplayValue = false)]
public string TypeImageURL { get; set; }
}
Notice I have a "TypeImageFile" HttpPostedFileBase
I would expect that the model binder would bond that property from the form to the model passes to the controller bu I just keep receiving null.
here is the relevant code in the View:
#using (Html.BeginForm("AddFaultType","Administration", FormMethod.Post))
{
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×</button>
<h3 id="myModalLabel">#SharedStrings.Add #SharedStrings.FaultType</h3>
</div>
<div class="modal-body">
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.TypeName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TypeName)
#Html.ValidationMessageFor(model => model.TypeName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.TypeDescription)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TypeDescription)
#Html.ValidationMessageFor(model => model.TypeDescription)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.TypeImageFile)
</div>
<div class="editor-field">
<input type="file" name="TypeImageFile" id="TypeImageFile" />
</div>
</div>
<div class="modal-footer">
<input type="submit" value="#SharedStrings.Add" class="btn btn-primary" />
#Html.ActionLink(SharedStrings.Cancel, "Index", "Administration", null, new { Class = "btn", data_dismiss = "modal", aria_hidden = "true" })
</div>
}
and here is the controller:
[HttpPost]
public ActionResult AddFaultType(FaultTypeViewModel i_FaultToAdd)
{
var fileName = Path.GetFileName(i_FaultToAdd.TypeImageFile.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
i_FaultToAdd.TypeImageFile.SaveAs(path);
return RedirectToAction("Index");
}
Make sure you've set the enctype attribute on your form to multipart/form-data on your form if you want to be able to upload files:
#using (Html.BeginForm("AddFaultType", "Administration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
}
Completing Darin's answer:
Make sure you've set the enctype attribute on your form to multipart/form-data on your form if you want to be able to upload files:
#using (Html.BeginForm("AddFaultType", "Administration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
}
To ensure your <input> is transmitted to the controller as part of the model use the Html Helpers for Id and name like below:
<input type="file" id="#Html.IdFor(x=>x.HttpPostedFileBase)" name="#Html.NameFor(x=>x.HttpPostedFileBase)" accept=".csv,.txt"/>
Works in MVC5 sorry I cant find any reference to which helpers are available in MVC3

Resources