I have problem. I open my website on for example on: localhost:9999/Product/Index
When I click Create icon that displays a modal popup with page /Product/Crate
I click Save.
All the records in the database correctly, but it redirects me to page /Product/Crate, and I would like to only close my modal window.
What sholuld I do?
Model:
public partial class Prod
{
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public byte[] PFile { get; set; }
}
Index View:
#using (Html.BeginForm("Create", "Products", FormMethod.Post, new {
enctype = "multipart/form-data" })){
#Html.ActionLink(" ", "Create", "Products", null, new { data_modal = "", id = "btnCreate", #class = "btn btn-small
btn-primary pull-right fa fa-cart-plus" })
#Html.ActionLink(" ", "Create", "Products", null, new { id =
"btnCreate", #class = "btn btn-small btn-primary pull-right fa
fa-cart-plus" }) }
Create View:
#using (Html.BeginForm("Create", "Products", FormMethod.Post, new { id = "form1", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ProductName, "Name", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.EditorFor(model => model.ProductName)
#Html.ValidationMessageFor(model => model.ProductName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductDescription, "Name", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.EditorFor(model => model.ProductDescription)
#Html.ValidationMessageFor(model => model.ProductDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PFile, "File", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.TextBoxFor(model => model.PFile, new { type = "file", name = "imageF" })
#Html.ValidationMessageFor(model => model.PFile, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Anuluj</button>
<input class="btn btn-primary" type="submit" value="Zapisz" />
</div>
}
Controller:
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = "PFile")] Prod pro, HttpPostedFileBase imageF)
{
if (ModelState.IsValid)
{
if (imageF != null)
{
pro.PFile= new byte[imageF.ContentLength];
imageF.InputStream.Read(pro.PFile, 0, imageF.ContentLength);
}
db.Prods.Add(pro);
db.SaveChanges();
return Json(new { success = true });
}
return PartialView("Create", pro);
}
modalform.js
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
// hide dropdown if any
$(e.target).closest('.btn-group').children('.dropdown-toggle').dropdown('toggle');
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
/*backdrop: 'static',*/
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form1', dialog).submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $('#file').serialize(),
contentType: 'multipart/form-data',
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
//Refresh
location.reload();
} else {
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
}); }
Please help to solve this.
Related
This question already has answers here:
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 4 years ago.
I use a code like this to receive customer information.
Along with my customer information, I must upload a file as well.
CSHTML File
#using (Html.BeginForm("AddPersonInfo", "Management", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmAddPerson" })) { #Html.AntiForgeryToken()
<div id="divControls" class="form inline">
<div class="form-group">
#Html.LabelFor(model => model.FName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-12">
#Html.EditorFor(model => model.FName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LName, htmlAttributes: new { #class = "control-label col-md-2"})
<div class="col-md-12">
#Html.EditorFor(model => model.LName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FileName, htmlAttributes: new { #class = "control-label col-md-2", style = "float: right" })
<div class="col-md-12">
<input id="postedFile" type="file" data-buttonText="Select File">
#Html.ValidationMessageFor(model => model.FileName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input style="float: right" id="btnSave" type="button" value="Save" class="btn btn-info" />
</div>
</div>
</div>
}
Java Script File
<script>
$(document).ready(function () {
$("#btnSave").click(function (e) {
e.preventDefault();
if ($("#frmAddPerson").valid()) {
var formData = new FormData();
var file = document.getElementById("postedFile").files[0];
formData.append("postedFile", file);
$.ajax({
url: "/Management/AddPersonInfo",
data: formData,
type: "Post",
dataType: "Json",
contentType: false,
processData: false,
success: function (result) {
alert("success")
},
error: function (result) {
alert("error");
}
});
}
});
});
</script>
Controller File
public ActionResult AddPersonInfo(PersonViewModel model, HttpPostedFileBase postedFile)
{
try
{
//
}
catch
{
//
}
}
In the AddPersonInfo in Controller, the file information (postedFile) will be received correctly But the form information (model) will be received null
In the ajax request, you are only adding the postedFile to your FormData()
var formData = new FormData();
var file = document.getElementById("postedFile").files[0];
formData.append("postedFile", file);
Try adding the model by hand,
var formData = new FormData();
var file = document.getElementById("postedFile").files[0];
formData.append("postedFile", file);
var model: {
'FName' : 'John',
'LName' : 'Smith'
}
formData.append('model', model);
I'm using this jQuery from CodePen https://codepen.io/dicson/pen/eJzoEX & it's working great however it is somehow blocking the FormMethod.Post action from firing. I'm not very experienced with JS / JQuery so hoping someone can help.
FORM
#using (Html.BeginForm("Login", "Authentication", FormMethod.Post, new { role = "form" }))
{
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<form class="form">
<div class="f_row">
<label>Username</label>
#Html.TextBoxFor(m => m.Email, new { #name = "username", #type = "username", #class = "input-field", #required = "" })
#Html.ValidationMessageFor(m => m.Email, "", new { #class = "text-danger" })
<u></u>
</div>
<div class="f_row last">
<label>Password</label>
#Html.PasswordFor(m => m.Password, new { #name = "pass", #type = "password", #class = "input-field", #required = "" })
#Html.ValidationMessageFor(m => m.Password, "", new { #class = "text-danger" })
<u></u>
</div>
<div class="form-group">
<input type="submit" value="GO" class="btn btn-default submit-btn input-field" />
</div>
</form>
}
JQUERY
var inP = $('.input-field');
inP.on('blur', function () {
if (!this.value) {
$(this).parent('.f_row').removeClass('focus');
} else {
$(this).parent('.f_row').addClass('focus');
}
}).on('focus', function () {
$(this).parent('.f_row').addClass('focus');
$('.btn').removeClass('active');
$('.f_row').removeClass('shake');
});
$('.resetTag').click(function(e){
e.preventDefault();
$('.formBox').addClass('level-forget').removeClass('level-reg');
});
$('.back').click(function(e){
e.preventDefault();
$('.formBox').removeClass('level-forget').addClass('level-login');
});
$('.regTag').click(function(e){
e.preventDefault();
$('.formBox').removeClass('level-reg-revers');
$('.formBox').toggleClass('level-login').toggleClass('level-reg');
if(!$('.formBox').hasClass('level-reg')) {
$('.formBox').addClass('level-reg-revers');
}
});
$('.btn').each(function() {
$(this).on('click', function (e) {
e.preventDefault();
var finp = $(this).parent('form').find('input');
console.log(finp.html());
if (!finp.val() == 0) {
$(this).addClass('active');
}
setTimeout(function () {
inP.val('');
$('.f_row').removeClass('shake focus');
$('.btn').removeClass('active');
}, 2000);
if (inP.val() == 0) {
inP.parent('.f_row').addClass('shake');
}
//inP.val('');
//$('.f_row').removeClass('focus');
});
});
If I dont load the jquery the form works fine.
I get an undefined log on the console when running the jquery
I am trying to Post a Partial View's data to the server to save the input fields result to database and then return back to the same (partial view which is open as a modal dialog) or return to the parent view which called the modal dialog.
But for some reason, I am not getting the Action method's parameter (i.e. weldMaster) in the Controller which is being sent from the ajax method call.
Here is my controller method.
// GET: WeldMasters/Details/5
public ActionResult Details(int? ids, bool isPartials = false)
{
if (ids == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
WeldMaster weldMaster = db.WeldMasters.Find(ids);
ViewBag.Readonly = false;
if (weldMaster == null)
{
return HttpNotFound();
}
if(isPartials)
return PartialView(weldMaster);
else
return View(weldMaster);
}
// POST: WeldMasters/Details/5
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Details**(WeldMaster weldMaster)**
//{"The parameter conversion from type 'System.String' to type 'IMCC_PAS.Entities.WeldMaster' failed because no type converter can convert between these types."}
{
var success = 0;
if (ModelState.IsValid)
{
success = 1;
db.Entry(weldMaster).State = EntityState.Modified;
db.SaveChanges();
return Json(new { success });
}
return Json(new { success });
}
Here is the ajax code
<script type="text/javascript">
$(document).ready(function () {
$(".saveBtn").click(function (e) {
debugger;
var token = $('input[name="__RequestVerificationToken"]').val();
// If I dont pass the token in the `data` parameter of ajax, then action method of controller is not called at all.
e.preventDefault();
$.ajax({
type: "POST",
url: '#Url.Action("Details", "WeldMasters")',
data: { __RequestVerificationToken: token, weldMaster: $('#__AjaxAntiForgeryForm').serialize() },
success: function (result) {
alert(result);
},
failure: function (response) {
alert(result.responseText);
},
error: function (response) {
alert(result.responseText);
}
});
});
});
</script>
Here is the modal for the partial view
#model IMCC_PAS.Entities.WeldMaster
and here is the form
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.id)
<div class="row">
<div class="col-md-3 col-sm-12">
#Html.LabelFor(model => model.weld_no, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-3 col-sm-12">
#Html.LabelFor(model => model.rep_no, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-3 col-sm-12">
#Html.LabelFor(model => model.length, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-3 col-sm-12">
#Html.LabelFor(model => model.normal_size, htmlAttributes: new { #class = "control-label" })
</div>
</div>
<div class="row">
<div class="col-md-3 col-sm-12">
#Html.EditorFor(model => model.weld_no, ViewBag.Readonly ? (object)new { htmlAttributes = new { #readonly = "readonly", #class = "form-control" } } : new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-3 col-sm-12">
#Html.EditorFor(model => model.rep_no, ViewBag.Readonly ? (object)new { htmlAttributes = new { #readonly = "readonly", #class = "form-control" } } : new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-3 col-sm-12">
#Html.EditorFor(model => model.length, ViewBag.Readonly ? (object)new { htmlAttributes = new { #readonly = "readonly", #class = "form-control" } } : new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-3 col-sm-12">
#Html.EditorFor(model => model.normal_size, ViewBag.Readonly ? (object)new { htmlAttributes = new { #readonly = "readonly", #class = "form-control" } } : new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group modal-footer">
<div class="col-md-12">
<a class="saveBtn" href="javascript:void(0);">Edit</a>
</div>
</div>
</div>
}
EDIT: Here is the parent view which has the selection parameters for showing the weld details. And then Weld details are shown in a div (for readonly purpose) and can be edited in a popup modal dialog on a button click.
<script>
$(document).ready(function () {
... more code for other dropdowns here
//When Wled No is changed, reload Weld Details in its respective Partial view
$("#weldddl").change(function () {
var parameter = { ids: $("#weldddl").val(), isPartials: true };
$.ajax({
url: '/WeldMasters/Details/',
type: 'GET',
data: parameter,
success: function (result) {
var div = $('#weldDetails');
div.html('');
div.html(result);
}
});
});
$(".editWeldBtn").click(function () {
//debugger;
$('#MyModal').empty();
$('#MyModal').append(GetModalDialog());
var link = '#Url.Action("Details", "WeldMasters")';
data = { ids: $("#weldddl").val(), isPartials: true };
LaunchModalDlg(link, data, "View Weld Master Information", "75%");
});
});
</script>
<h4>Index</h4>
<script src="~/Scripts/MyScripts.js"></script>
<p>
#Html.ActionLink("Create New", "Create") |
<a class="editWeldBtn" href="javascript:void(0);">Edit</a>
</p>
<div class="row">
<div class="col-sm-3">
#Html.LabelFor(model => model.Discipline, htmlAttributes: new { #class = "control-label col-md-12" })
<div class="col-md-12">
#Html.DropDownListFor(model => model.Discipline, (SelectList)ViewBag.disciplines, htmlAttributes: new { #class = "form-control", #id = "disciplineddl" })
#Html.ValidationMessageFor(model => model.Discipline, "", new { #class = "text-danger" })
</div>
#Html.LabelFor(model => model.DrawingNo, htmlAttributes: new { #class = "control-label col-md-12" })
<div class="col-md-12">
#Html.DropDownListFor(model => model.DrawingNo, (SelectList)ViewBag.drawings, htmlAttributes: new { #class = "form-control", #id = "drawingddl" })
#Html.ValidationMessageFor(model => model.DrawingNo, "", new { #class = "text-danger" })
</div>
#Html.LabelFor(model => model.ComponentNo, htmlAttributes: new { #class = "control-label col-md-12" })
<div class="col-md-12">
#Html.DropDownListFor(model => model.ComponentNo, (SelectList)ViewBag.components, htmlAttributes: new { #class = "form-control", #id = "componentddl" })
#Html.ValidationMessageFor(model => model.ComponentNo, "", new { #class = "text-danger" })
</div>
#Html.LabelFor(model => model.WeldNo, htmlAttributes: new { #class = "control-label col-md-12" })
<div class="col-md-12">
#Html.DropDownListFor(model => model.WeldNo, (SelectList)ViewBag.components, htmlAttributes: new { #class = "form-control", #id = "weldddl" })
#Html.ValidationMessageFor(model => model.WeldNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-9" id="weldDetails"> <!--This is for showing the partial view for showing weld details-->
</div>
<div id="MyModal"></div> <!--This is for pop up modal dialog-->
</div>
If you are serializing the full form then you don't need to send explicitly anti forgery token.
use this:
data: $('#__AjaxAntiForgeryForm').serialize(),
JS:
<script type="text/javascript">
$('#dialog').dialog({
autoOpen: false,
width: 600,
modal: true,
buttons: {
"Yes": function () {
$("#DSCreateForm").submit(); // part that isn't working correctly
},
"Cancel": function () { $(this).dialog("close"); }
}
});
var hobbsValue = $('#HobbsValue').val();
alert(hobbsValue);
if (hobbsValue == null || hobbsValue.length == 0) {
$('.btnSubmitDS').on("click", function (e) {
e.preventDefault();
$(function () {
$('#dialog').dialog('open')
});
});
}
</script>
CSHTML:
#using (Html.BeginForm("Create", "DailySummaries", FormMethod.Post, new { id = "DSCreateForm" }))
<div class="form-group">
#Html.LabelFor(model => model.Hobbs, "HOBBS:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Hobbs, new { htmlAttributes = new { id = "HobbsValue", #class = "form-control hobbs-textbox", #placeholder = "xxxx.x" } })
#Html.ValidationMessageFor(model => model.Hobbs, "", new { #class = "text-danger" })
</div>
</div>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "...")] DailySummary dailySummary)
{
In the above code, when the 'Yes' button is selected, it is submitting but when I debugged it isn't going to the HttpPost Method of the controller. How do I get it to do so?
I'm making the bold assumption that you haven't set
method="post"
On your form?
Edit: now you've supplied your form create code, I can see that isn't the case.
I'm trying to implement a system where the value within a text box is passed onto a partial view, where it will present the details corresponding to that value. So for instances if Job "1" was within the text box , the partial view will return the details of that job for the user to change etc. Any Ideas on how to pass the value to the controller then the partial view?
Job.js
$(document).ready(function () {
$('#qr-value').on('change', function () {
if ($('#qr-value').val() == 'Job 1') {
$("#second").show(1000);
}
});
});
CameraInfo (partial view)
model JobTracker.Models.Job
<h2>Edit and Confirm</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Job</legend>
#Html.HiddenFor(model => model.JobID)
<div class="editor-label">
#Html.LabelFor(model => model.OrderID, "Order")
</div>
<div class="editor-field">
#Html.DropDownList("OrderID", String.Empty)
#Html.ValidationMessageFor(model => model.OrderID)
</div><br />
<div class="editor-label">
#Html.LabelFor(model => model.LocationID, "Location")
</div>
<div class="editor-field">
#Html.DropDownList("LocationID", String.Empty)
#Html.ValidationMessageFor(model => model.LocationID)
</div><br />
<div class="editor-label">
#Html.LabelFor(model => model.HighPriority)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.HighPriority, new SelectList(
new[]
{
new { Value = "Yes", Text = "Yes" },
new { Value = "No", Text = "No" },
},
"Value",
"Text",
Model
))
#Html.ValidationMessageFor(model => model.HighPriority)
</div><br />
<div class="editor-label">
#Html.LabelFor(model => model.Comments)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Comments)
#Html.ValidationMessageFor(model => model.Comments)
</div><br />
<div class="editor-label">
#Html.LabelFor(model => model.Status)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Status, new SelectList(
new[]
{
new { Value = "In Progress", Text = "In Progress" },
new { Value = "Completed", Text = "Completed" },
new { Value = "Not Started", Text = "Not Started" },
new { Value = "Stopped", Text = "Stopped" },
},
"Value",
"Text",
Model
))
#Html.ValidationMessageFor(model => model.Status)
</div><br />
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to Home Page", "Index","Home")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Job Controller.cs
//
// GET: /Job/Edit/5
public ActionResult Edit(int id = 0)
{
Job job = db.Jobs.Find(id);
if (job == null)
{
return HttpNotFound();
}
ViewBag.LocationID = new SelectList(db.Locations, "LocationID", "LocationName", job.LocationID);
ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderID", job.OrderID);
return View(job);
}
//
// POST: /Job/Edit/5
[HttpPost]
public ActionResult Edit(Job job)
{
if (ModelState.IsValid)
{
db.Entry(job).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.LocationID = new SelectList(db.Locations, "LocationID", "LocationName", job.LocationID);
ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderID", job.OrderID);
return View(job);
}
<div id='Sample'></div>
if you want to load the partial view use ajax.
$(document).ready(function () {
$('#qr-value').on('change', function () {
$.ajax({
type: "Get",
url: '#Url.Action("Edit", "job")',
data: { id: $('#qr-value').val()},
success: function (response) {
$('#Sample').html(response);
},
error: function (response) {
if (response.responseText != "") {
alert(response.responseText);
alert("Some thing wrong..");
}
}
});
});
});
[HttpGet]
public ActionResult Edit(int id = 0)
{
Job job = db.Jobs.Find(id);
if (job == null)
{
return HttpNotFound();
}
ViewBag.LocationID = new SelectList(db.Locations, "LocationID", "LocationName", job.LocationID);
ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderID", job.OrderID);
return PartialView("Edit",job);
}
Hope this helps