I have one form and one uploader (I use PLUploader) and want user fill textboxs and select image in PLUploader and when click on submit button,
I pass image and textboxs value to one action, I write this code, but always I get null in textboxs value but get image in action.
I think this problem related to call the one action with form and PLuploader.
public ActionResult Insert(News news, HttpPostedFileBase file)
{
// I get null in new but get file in HttpPostedFileBase
int result = 0;
HttpPostedFileBase FileData = Request.Files[0];
string fileName = null;
fileName = Path.GetFileName(FileData.FileName);
if (ModelState.IsValid)
{
//do some thing
}
else
{
return View(news);
}
}
#using (Html.BeginForm("Insert", "News", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="col-xs-12">
#Html.LabelFor(model => model.NewsTitle)
#Html.TextBoxFor(model => model.NewsTitle, new { #class = "form-control",#name="title" })
#Html.ValidationMessageFor(model => model.NewsTitle)
</div>
<div class="col-xs-12">
<div id="uploader" class="img-plc">
<p>You browser doesn't have Flash, Silverlight, Gears, BrowserPlus or HTML5 support.</p>
</div>
<ul id="gallery"></ul>
</div>
<div class="col-xs-12">
#Html.LabelFor(model => model.NewsText, new { #class = "text-right" })
#Html.ValidationMessageFor(model => model.NewsText)
#Html.TextAreaFor(model => model.NewsText, new { #rows = "10", #cols = "80", #class = "text-editor", #name = "title" })
</div>
<button type="submit">Submit</button>
}
var uploader = $("#uploader").pluploadQueue({
// General settings
runtimes: 'html5,gears,flash,silverlight,browserplus,html4',
url: '#Url.Action("Insert", "News")',
max_file_size: '10mb',
chunk_size: '1mb',
unique_names: true,
multi_selection: false,
multiple_queues: false,
// Specify what files to browse for
filters: [
{ title: "Image files", extensions: "jpg,png" }
],
// Flash settings
flash_swf_url: '/Scripts/Moxie.swf',
// Silverlight settings
silverlight_xap_url: '/Scripts/Moxie.xap'
})
$('form').submit(function (e) {
var uploader = $('#uploader').pluploadQueue();
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
} else {
alert('You must queue at least one file.');
}
return false;
});
How can I fix this? I want to get news and file in this action.
Create a ViewModel to contain both properties
public class NewsViewModel {
public News News { get; set; }
public HttpPostedFileBase File { get; set; }
}
public ActionResult Insert(NewsViewModel model) {
/* ... */
}
When you create the view pass the ViewModel into the view. Make sure you use the right name for the input field to make it bind correctly:
#Html.TextBoxFor(model => model.File, new { type = "file" })
I would assume you might have to tell your script what name the file input shoul have.
Related
I want to set default value which will miss when click on the dropdown list.I would like to be unable to select "Please select" value. When I click on "Please select" value in materialId or depotId, "" null value send by ajax and I am getting error. How can I prevent this?
Create.cshtml
<div class="form-group">
#Html.LabelFor(model => model.materialId, "Material names", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("materialId", null, "Please select", htmlAttributes: new { #class = "form-control chosen" })
#Html.ValidationMessageFor(model => model.materialId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.depotId, "Product Outlet", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("depotId", null, "Please select", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.depotId, "", new { #class = "text-danger" })
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#depotId').change(function () { sendDataByAjax(); });
$('#materialId').change(function () { sendDataByAjax(); });
})
function sendDataByAjax() {
var materialId= $('#materialId option:selected').val();
var depotId= $('#depotId option:selected').val();
if (materialId == "" || depotId == "") {
// I can not write this
}
$.ajax({
type: "GET",
url: "#Url.Action("GetStock", "OutgoingProduct")",
data: {
'materialId': materialId,
'depotId': depotId
},
success: function (data) {
$("#stock").html(data);
}
});
}
</script>
}
I am getting error here when "" goes to my controller. Because it is not int.
OutgoingProductController.cs
public string GetStock(string materialId, string depotId)
{
int did = int.Parse(depotId);
int mid = int.Parse(materialId);
Since your dropdownlist selected values are passed as numeric values, you may use parseInt() function to try parsing numeric value from client-side and then check against NaN, if the value is numeric then trigger AJAX callback:
function sendDataByAjax() {
var materialId = parseInt($('#materialId option:selected').val());
var depotId = parseInt($('#depotId option:selected').val());
if (isNaN(materialId) || isNaN(depotId)) {
// do something, e.g. alert user
return false;
}
else {
$.ajax({
type: "GET",
url: "#Url.Action("GetStock", "OutgoingProduct")",
data: {
'materialId': materialId,
'depotId': depotId
},
success: function (data) {
$("#stock").html(data);
}
});
}
}
Then make sure that your action method contains int type for both parameters, hence no need to use int.Parse() which will throwing exception if parsed string has null value:
public ActionResult GetStock(int materialId, int depotId)
{
int did = depotId;
int mid = materialId;
// other stuff
}
Try returning false when materialId == "" || depotId == "" :
function sendDataByAjax() {
var materialId= $('#materialId option:selected').val();
var depotId= $('#depotId option:selected').val();
if (materialId == "" || depotId == "") {
return false;
}
$.ajax({
type: "GET",
url: "#Url.Action("GetStock", "OutgoingProduct")",
data: {
'materialId': materialId,
'depotId': depotId
},
success: function (data) {
$("#stock").html(data);
}
});
}
the way to solve this is not the way you're trying to do it. the way to do should be to use the validation system, available for MVC.
Change your get method to use a model, something like:
public class StockRequestModel
{
[Required]
public int materialId { get; set }
[Required]
public int depoId { get;set; }
}
Your controller method can then become something like:
public string GetStock([FromUri] StockRequestModel model)
{
if ( !ModelState.IsValid )
{
some code here
}
//at this point your model is valid and you have IDs so can proceed with your code
}
Normally, in MVC you would return the original View with the state in the result, so you can then trigger the front end validation. In your case, you seem to have a WebAPI controller in an MVC app, but you can still use front end validation.
There are other questions related to yours, such as Client side validation with Angularjs and Server side validation with Asp.net MVC
Normally I'd vote to close it as duplicate, but in this case, I think it's worthwhile pointing out the issue and solution.
Another place to go would be https://angularjs.org/ and then check the Form Validation section for pure front end validation. Of course you'd want to keep both front end and back end validations.
I want to save the file path to my database reports table. I have a column of type: string FilePath.
The end goal is that I want to be able to download the file from a report details view. Obviously the report download link would be different depending on the report ID.
Currently it doesn't seem that the controller is receiving anything as before I had Object reference not set to an instance of an object exception. I then added file != null in my if statement so I don't get the error anymore. However clearly the underlying issue is still present. Here is my controller save action:
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "AdminManager")]
public ActionResult Save(Report report, HttpPostedFileBase file)
{
if (!ModelState.IsValid)
{
var viewModel = new ReportFormViewModel
{
Report = report,
Members = _context.Members.ToList(),
Subjects = _context.Subjects.ToList()
};
return View("ReportForm", viewModel);
}
if (file != null && file.ContentLength > 0)
{
string filePath = Path.Combine(
Server.MapPath("~/App_Data/Uploads"),
Path.GetFileName(file.FileName));
file.SaveAs(filePath);
}
if (report.Id == 0)
_context.Reports.Add(report);
else
{
var reportInDb = _context.Reports.Single(e => e.Id == report.Id);
reportInDb.Name = report.Name;
reportInDb.MemberId = report.MemberId;
reportInDb.SubjectId = report.SubjectId;
reportInDb.Date = report.Date;
reportInDb.FilePath = report.FilePath;
}
_context.SaveChanges();
return RedirectToAction("Index", "Report");
}
Here is my form view:
<h2>#Model.Title</h2>
#using (Html.BeginForm("Save", "Report", new {enctype = "multipart/form-data"}))
{
<div class="form-group">
#Html.LabelFor(r => r.Report.Name)
#Html.TextBoxFor(r => r.Report.Name, new { #class = "form-control" })
#Html.ValidationMessageFor(r => r.Report.Name)
</div>
<div class="form-group">
#Html.LabelFor(r => r.Report.Date) e.g. 01 Jan 2000
#Html.TextBoxFor(r => r.Report.Date, "{0: d MMM yyyy}", new { #class = "form-control" })
#Html.ValidationMessageFor(r => r.Report.Date)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Report.MemberId)
#Html.DropDownListFor(m => m.Report.MemberId, new SelectList(Model.Members, "Id", "Name"), "Select Author", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Report.MemberId)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Report.SubjectId)
#Html.DropDownListFor(m => m.Report.SubjectId, new SelectList(Model.Subjects, "Id", "Name"), "Select Subject", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Report.SubjectId)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Report.FilePath)
<input type="file" name="file" id="file"/>
</div>
#Html.HiddenFor((m => m.Report.Id))
#Html.AntiForgeryToken()
<button type="submit" class="btn btn-primary">Save</button>
}
Current code doesn't seem to send file data to action.
It is recommended to add the file to your model:
public class Report {
[Required]
[Display(Name = "Report File")]
public HttpPostedFileBase ReportFile { get; set; }
//... The other fields
}
Usually I would append ViewModel, so ReportViewModel instead of Report. This makes it easier to distinguish between view models and business/data models.
And in your Razor:
<div class="form-group">
#Html.LabelFor(m => m.Report.ReportFile)
#Html.TextBoxFor(m => m.ReportFile, new { type = "file" })
<!--You can also use <input type="file" name="ReportFile" id="ReportFile"/>-->
</div>
Note that the name that you use in the LabelFor must match the ID of the control. In your code FilePath and file didn't match.
And finally in the controller:
public ActionResult Save(Report report)
{
//...some code
string filePath = Path.Combine(Server.MapPath("~/App_Data/Uploads"),
Path.GetFileName(report.ReportFile.FileName));
report.ReportFile.SaveAs(filePath);
//...other code
}
I wouldn't use the name of the uploaded file. Instead, I would give it a name according to my project's naming convention. I often use the ID as the name, perhaps with some prefix. Example:
var fileName = "F" + report.Id + ".jpg"; //You can get the extension from the uploaded file
string filePath = Path.Combine(Server.MapPath("~/App_Data/Uploads"), fileName);
Obviously, when you're inserting a new object, you won't have an ID until you insert it into the database, so the code to save the physical file must be placed after the code to insert it into the database. If you follow this logic, you don't need to save the path in the database, because the path can be always calculated from the ID. So you save a column in the database, gain performance in your code as you don't need to handle another string column, and you have a clear and simply file naming convention that is safe without user input risk.
Another way I follow, especially when the type of the file may vary (i.e. you can upload files with different extensions), is using a GUID for the file name. In this case, the file name must be saved in the database, but the GUID can be generated before inserting the object into the database. Example:
string ext = report.ReportFile.FileName.Substring(
report.ReportFile.FileName.LastIndexOf('.')).ToLower();
var fileName = Guid.NewGuid().ToString() + ext;
string filePath = Path.Combine(Server.MapPath("~/App_Data/Uploads"), fileName);
I need a help.
I have a User registration form and I have to map "Customer" with user.
Now I want to validate user "customer" which is came from another source and I put the "customer" in Select list "customer" are more then 2000 that's why I use JQuery Chosen plugin to search in select list
but "customer" Field depend on "roles" that's why on page load "customer" field is hidden by default when I change the role "customer" field(chosen select list) display and when i am Selecting customer its not firing remote validation.
I tried to make it visible on "inspect element" and I change the display:none to display:bock and try to change value from chosen its not working when i change the orignal select list value from clicking on select list then its working fine i mean its firing my remote validator method here is full code example what i am doing.
please help i want to validate on when chosen select list value change.
This is RegisterViewModel
public class RegisterViewModel
{
[Required]
[Display(Name = "Role")]
public string Role { get; set; }
//for edit view model additionalFields which will only require for edit mode
//[System.Web.Mvc.Remote("DoesCustomerCodeExist", "Account", AdditionalFields = "OldCustomerCode")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Customer Code is required.")]
[Display(Name = "Customer Code", Description = "A customer code come from our oracle system.")]
[System.Web.Mvc.Remote("DoesCustomerCodeExist", "Account")]
[Range(0, int.MaxValue, ErrorMessage = "Please enter valid Customer Code in number only.")]
public string CustomerCode { get; set; }
}
Here is my view cshtml in this file also have js code to display customers chosen Select list when role changed.
//select Role
<div class="form-group">
#Html.LabelFor(m => m.Role, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(x => x.Role, ViewBag.Roles as SelectList,"", new { #class = "form-control chosen-select", data_placeholder = "Select a Role" })
#Html.ValidationMessageFor(m => m.Role, "", new { #class = "text-danger" })
</div>
</div>
//Customer Code
<div class="form-group condition-div user hidden ">
//this hidden field is only for edit mode
//#Html.Hidden("OldCustomerCode", Model.CustomerCode)
#Html.LabelFor(m => m.CustomerCode, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(x => x.CustomerCode, (SelectList)ViewBag.Customers, "", new { #class = "form-control chosen-customers", data_placeholder = "Select Customer" })
#Html.ValidationMessageFor(m => m.CustomerCode, "", new { #class = "text-danger" })
</div>
</div>
#section Styles{
#Styles.Render("~/Content/chosen")
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/chosen")
<script type="text/javascript">
$('input[type=text]').tooltip(
{
placement: "right",
trigger: "focus"
}
);
$(".chosen-select").chosen({ allow_single_deselect: true});
$('#Role').change(function () {
if (this.value == "") {
$('.condition-div').addClass('hidden'); // hide all the conidional divs
} else if (this.value == "NBP User" || this.value == "NBP Head" ) {
$('.condition-div.admin').addClass('hidden'); /// hide admin conditional divs
$('.condition-div.user').removeClass('hidden'); // show user role conditioanl div
//configure selectlist to Chosen select and if i remove this line and show orignal select list its working fine mean remote validating on change but if i use this is not working on change.
$(".chosen-customers").chosen({ allow_single_deselect: true, search_contains: true });
$.validator.setDefaults({ ignore: ":hidden:not(.chosen-customers)" });
} else if (this.value == "ICIL User" || this.value == "ICIL Head" || this.value == "FIO User" ) {
$('.condition-div.user').addClass('hidden'); /// hide user role conditional divs
$('.condition-div.admin').removeClass('hidden'); // show admin role conditional divs
$(".chosen-branch").chosen({ allow_single_deselect: true });
$.validator.setDefaults();
}
});
</script>
}
Controller Action to validate Customer Code
public ActionResult DoesCustomerCodeExist(string CustomerCode, string OldCustomerCode)
{
//the oldCustomerCode will come null in this case cause its register view and in edit view OldCustomerCode will be use
if (CustomerCode == OldCustomerCode)
return Json(true, JsonRequestBehavior.AllowGet);
if (DbContext.Users.Any(x => x.CustomerCode == CustomerCode))
return Json("Customer code already exists in application. Please verify user details.", JsonRequestBehavior.AllowGet);
if (DbOracle.IsCustomerCodeExist(CustomerCode))
return Json(true, JsonRequestBehavior.AllowGet);
else
return Json("The customer code does not exist in database.", JsonRequestBehavior.AllowGet);
}
All code working fine if i did not use jquery chosen plugin.
In short issue is when I use chosen plugin for select list remote validation is stop validating values.
I can share images if u guys need now I have a limited account so i cant upload snaps shots....
Please help me.
you should have to put some JQuery on client side to track the "CustomerCode" field when change of customer field jsut call "focusout()" event of "CustomerCode" e.g:
$('#CustomerCode').change(function () {
$(this).focusout();
});
I have following GET method , that's a code to a create form
public ActionResult Add_Product(string Product_ID)
{
AddNewProduct sample = new AddNewProduct();
return View(sample);
}
this is the model class for that
public class AddNewProduct
{
public string Product_ID { get; set; }
...
}
this is that create form
#model project_name.Models.AddNewProduct
<h4>Add New Product</h4>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" }) <div class="form-group">
#Html.LabelFor(model => model.Product_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Product_ID, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Product_ID, "", new { #class = "text-danger" })
</div>
</div>
.....
<div>
#Html.ActionLink("Back to AddNewProduct", "AddNewProduct","Home" , new {Product_ID = Model.Product_ID})
</div>
}
I can Insert a Product_ID using this view page .But Once I click this Back to AddNewProduct link and debug AddNewProduct I cannot see any value for string Product_ID
Why this model properties not bind well
You need to assign value. Assign value of Product_ID which you are sending from get method to Product_ID property of class
public ActionResult Add_Product(string Product_ID)
{
AddNewProduct sample = new AddNewProduct();
sample.Product_ID = Product_ID;
return View(sample);
}
To pass the value of the textbox to the Add_Product() GET method, you need to use javascript/jquery. Replace you #Html.ActionLink(..) with
Back to AddNewProduct
and add the following script
var baseUrl = '#Url.Action("Add_Product", "Home")';
$('#back').click(function() {
var id = $('#Product_ID').val();
location.href = baseUrl + '/' + id;
}}
Note: location.href = baseUrl + '/' + id; assumes your have defined a specific route with {controller}/{action}/{Product_ID}, otherwise it needs to be
location.href = baseUrl + '?Product_ID=' + id;
Alternatively, change the method parameter to string id so it uses the default route
Note also that you will probably want to change the method to
public ActionResult Add_Product(string Product_ID)
{
AddNewProduct sample = new AddNewProduct
{
Product_ID = Product_ID
};
return View(sample);
}
so that if you click the Back to AddNewProduct link, the view will display the previous value you entered.
The second parameter of the #Html.ActionLink is the actionName but you sent the model name (AddNewProduct). Change it to this:
#Html.ActionLink("Back to AddNewProduct", "Add_Product","Home" , new {Product_ID = Model.Product_ID})
Or use this overload (You need to send null also when using this ActionLink overload):
#Html.ActionLink("Back to AddNewProduct", "Add_Product","Home" , new {Product_ID = Model.Product_ID}, null)
i have one form and one uploader (i use PLUploader) and want user fill textboxs and select image in PLUploader and when click on submit button , i pass image and textboxs value to one action , i write this code, but alwaye i get null in textboxs value but get image in action ,i think this problem related to call the one action with form and PLuploader,
public ActionResult Insert(News news, HttpPostedFileBase file)
{
// i get null in new but get file in HttpPostedFileBase
int result = 0;
HttpPostedFileBase FileData = Request.Files[0];
string fileName = null;
fileName = Path.GetFileName(FileData.FileName);
if (ModelState.IsValid)
{
//do some thing
}
else
{
return View(news);
}
}
#using (Html.BeginForm("Insert", "News", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="col-xs-12">
#Html.LabelFor(model => model.NewsTitle)
#Html.TextBoxFor(model => model.NewsTitle, new { #class = "form-control",#name="title" })
#Html.ValidationMessageFor(model => model.NewsTitle)
</div>
<div class="col-xs-12">
<div id="uploader" class="img-plc">
<p>You browser doesn't have Flash, Silverlight, Gears, BrowserPlus or HTML5 support.</p>
</div>
<ul id="gallery"></ul>
</div>
<div class="col-xs-12">
#Html.LabelFor(model => model.NewsText, new { #class = "text-right" })
#Html.ValidationMessageFor(model => model.NewsText)
#Html.TextAreaFor(model => model.NewsText, new { #rows = "10", #cols = "80", #class = "text-editor", #name = "title" })
</div>
<button type="submit">Submit</button>
}
var uploader = $("#uploader").pluploadQueue({
// General settings
runtimes: 'html5,gears,flash,silverlight,browserplus,html4',
url: '#Url.Action("Insert", "News")',
max_file_size: '10mb',
chunk_size: '1mb',
unique_names: true,
multi_selection: false,
multiple_queues: false,
// Specify what files to browse for
filters: [
{ title: "Image files", extensions: "jpg,png" }
],
// Flash settings
flash_swf_url: '/Scripts/Moxie.swf',
// Silverlight settings
silverlight_xap_url: '/Scripts/Moxie.xap'
})
$('form').submit(function (e) {
var uploader = $('#uploader').pluploadQueue();
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
} else {
alert('You must queue at least one file.');
}
return false;
});
how i can fixed this ?
i want get news and file in this action
thank you
you're not submitting your whole form; instead you're capturing the submit action with the jQuery event handler for onSubmit:
$('form').submit(function (e) { ... });
If you want to do it this way, you'll have to serialize your News model inside this jQuery code block as well and post it along with the file upload.
I would just stick the HttpPostedFileBase inside the News model and use the normal form submit though.