how to send a form that contains another form - javascript

I have a form that contains another form.
the first form sends data to the action indicated in the beginform which the particular form it contains.
The second form ( contained in the first ) is a list that on change event, exchange a picture, this works .
but the first form is not sent yet.
how can I do to submit the first form normaly and the second with the javascript on change ?
#using (Html.BeginForm("VCreateCommande", "CCommande", new {id="formretouche"}, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
var imagedefaut = "";
#Html.AntiForgeryToken()
<h4>Retouchephoto</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group ilnblk">
<div class="control-label col-md-2 fltleft">Type de retouche</div>
<div class="col-md-10 fltleft">
#using (Html.BeginForm("VCreateCommande", "CCommande", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.DropDownListFor(model => model.Ttyperetouche.Idtyperetouche, new SelectList(
Model.Ttyperetouches, "Idtyperetouche", "libelle", ViewData["Idtyperetouche"]), new { #onchange = "this.form.submit()" })
} </div>
<div class="fltleft imagemodele">
#if (ViewData["Idtyperetouche"] != null)
{
foreach (var typeretouche in Model.Ttyperetouches)
{
if (typeretouche.Idtyperetouche.ToString() == ViewData["Idtyperetouche"].ToString())
{
imagedefaut = typeretouche.SRCtyperetouche;
}
}
}
else
{
imagedefaut = Model.Ttyperetouches.First().SRCtyperetouche;
}
<img src="#imagedefaut" />
</div>
</div>
<div class="form-group">
<div class="control-label col-md-2">Support papier</div>
<div class="col-md-10">
#Html.CheckBoxFor(model => model.Tretouche.Supportpapier, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Tretouche.Supportpapier, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="control-label col-md-2">Quantité</div>
<div class="col-md-10">
#Html.EditorFor(model => model.Tretouche.Quantite, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Tretouche.Quantite, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="control-label col-md-2">Photo...</div>
<div class="col-md-10">
#Html.TextBoxFor(model => model.Tretouche.fichierphoto, new { type = "file" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
#{
String onclick = String.Format("Submit(this)",
Html.Encode(ViewBag.returnUrl));
}
<input type="button" id="btnsubmitretouche" value="Ajouter1" onclick="#onclick" />
<input type="submit" value="Ajouter" class="btn btn-default"/>
</div>
</div>
}

It is not valid html5 to nest forms, see the W3C HTML5 Working Draft.

Related

Jquery - Button isn't disabling after being clicked

I am trying to disable my button after it's clicked but it isn't working I have looked at multiple solutions online but nothing is working for me at the moment so I want to know what I am doing wrong.
Here is my file, where I have tried a solution recommends in the answers by #SLePort
#model PIC_Program_1._0.Models.JobOrder
#{
ViewBag.Title = "Change Status";
}
<script type="text/javascript">
$('form').submit(function (e) {
e.preventDefault();
$('input[type="submit"]').prop("disabled", true);
})
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
#using PIC_Program_1._0.Models
<h2>Change Status</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.Raw(IGT.Format(WebUtility.HtmlDecode(Convert.ToString(Html.ValidationSummary(true, "", new { #class = "text-danger" })))))
<input type="hidden" name="origin" value="#ViewBag.Origin" />
<div class="form-horizontal">
<h4>Work Order</h4>
<br />
<p><b><u>Order Details:</u></b></p>
#{
if (Model.Status == JOStatus.Pending && Model.hasBeenStarted == false && Model.parentJobOrderID <= 0)
{
<div class="form-group">
#Html.LabelFor(model => model.dynamicOrder, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.dynamicOrder, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.dynamicOrder, "", new { #class = "text-danger" })
</div>
</div>
}
else
{
#Html.HiddenFor(model => model.dynamicOrder)
}
}
<div class="form-group">
#Html.LabelFor(model => model.Status, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Status, new SelectList(ViewBag.statusList, "value", "text"), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Status, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Details, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.Details, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Details, "", new { #class = "text-danger" })
</div>
</div>
<form>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn" />
</div>
</div>
</form>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Here is a few jquery things that I have tried
<script type="text/javascript">
$('form').submit(function () {
$(':submit').prop("disabled", "disabled");
})
$('input[type=submit]').one('submit', function () {
$(this).attr('disabled', 'disabled');
});
$('#form-group').one('submit', function () {
$(this).find('input[type="submit"]').attr('disabled', 'disabled');
});
</script>
Any help would be much appreciated.
Try to add a preventDefault() to prevent button from disappearing after page reloads and set the disabled prop with a true value:
$('form').submit(function(e) {
e.preventDefault();
$('input[type="submit"]').prop("disabled", true);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn" />
</div>
</div>
</form>

How to open a dialog box after submit a form to show posted successfully - asp.net MVC

I'm working on a asp.net MVC project. I want to show user a dialog box after form posted, for user to understand if it was successful or not, and also if user wants to close the dialog box it would be possible.
I searched a lot and read something that I can return partial view but i'm not sure if partial view is what I need in this situation
my question is that is it possible to do it a way with java-script with .dialog() or if I should use partial view, then please give me a little explanation how it works.
I need something like this to show after user click on submit button
http://jsfiddle.net/db5SX/
here is my controller:
public ActionResult Index()
{
ViewBag.ResultMessage = TempData["ResultMessage"];
return View();
}
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Email,Phone,Message,Date")] Contact_US contact_US)
{
if (ModelState.IsValid)
{
db.Contact_US.Add(contact_US);
db.SaveChanges();
TempData["ResultMessage"] = "POSTED SUCESSFULLY...! We WILL CONTACT YOU SOON.";
return RedirectToAction("Index");
}
return View(contact_US);
}
here is my view if needed:
<div class="form-group col-md-8">
<h3 class="txtformat padbot50px">Get in touch with us</h3>
<div class="text-danger message ">
#ViewBag.ResultMessage
</div>
#using (Html.BeginForm("Create", "Contact_Us", FormMethod.Post, new { #id = "contactusform" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2 txtformat" })
<div class="col-md-12">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2 txtformat" })
<div class="col-md-12">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2 txtformat" })
<div class="col-md-12">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group hidden">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Message, htmlAttributes: new { #class = "control-label col-md-2 txtformat" })
<div class="col-md-12 contactusmsg">
#Html.TextAreaFor(model => model.Message, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Message, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group contactuspostbtn">
<div class="col-md-12">
<input id="postcontactusmessage" type="submit" value="Send" class="btn btn-default" data-toggle="modal" data-target="#myModal" />
</div>
</div>
</div>
}
</div>
</div>
information of my layout if needed :
<script src="~/Scripts/jquery-3.1.0.min.js"></script>
<link href="~/Scripts/jquery-ui-1.12.1.custom/jquery-ui.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui-1.12.1.custom/jquery-ui.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/tinymce/tinymce.min.js"></script>
A good way to do this is to have it abstracted in a base controller and show the message in the _layouts.cshtml file, for example:
Create a base controller that will be inherited by all of your controllers
public class BaseController : Controller
{
public string SucccessMessage
{
get
{
return TempData["SuccessMessage"] as string;
}
set
{
TempData["SuccessMessage"] = value;
}
}
public string ErrorMessage
{
get
{
return TempData["ErrorMessage"] as string;
}
set
{
TempData["ErrorMessage"] = value;
}
}
}
In _Layouts.cshtml,
<div class="container body-content" id="bodyContainer">
<div class="spacer"></div>
#if (#TempData["SuccessMessage"] != null)
{
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
#TempData["SuccessMessage"]
</div>
}
else if (#TempData["ErrorMessage"] != null)
{
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
#TempData["ErrorMessage"]
</div>
}
<div class="spacer"></div>
#RenderBody()
<hr id="hr" />
<footer>
<p>© #DateTime.Now.Year - Your APp </p>
</footer>
</div>
Now, all you need to do inside your controller is:
public class MyController:BaseController
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Email,Phone,Message,Date")] Contact_US contact_US)
{
if (ModelState.IsValid)
{
db.Contact_US.Add(contact_US);
db.SaveChanges();
SucccessMessage = "POSTED SUCESSFULLY...! We WILL CONTACT YOU SOON.";
return RedirectToAction("Index");
}
return View(contact_US);
}
}

Upload image to database

Im trying to figure out how I can upload a profile image to my database within my asp.net mvc web project.
The issues is that im getting a Data URI instead of an actual file upload and that the URI is generated inside my javascript and im not sure how I can pass URI aswell as the other input fields inside my form to the controller.
View - Form
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.ProfilePicture, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<div id="wrapper" style="margin-top: 20px;">
<div class="image-editor">
<input type="file" class="cropit-image-input">
<div class="cropit-preview"></div>
<div class="image-size-label">
Resize image
</div>
<div class="controls-wrapper">
<div class="slider-wrapper">
<span class="icon icon-image small-image"></span>
<input type="range" class="cropit-image-zoom-input custom">
<span class="icon icon-image large-image"></span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.UserName, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="hidden" name="profilePicture" class="hidden-image-data">
<input type="submit" class="btn btn-default" value="Register"/>
</div>
</div>
}
Javascript below the Form
<script src="~/Scripts/jquery.cropit.js"></script>
<script>
$(function() {
$('.image-editor').cropit({
imageBackground: true,
imageBackgroundBorderWidth: 20,
initialZoom: 'image',
smallImage: 'stretch',
imageState: {
src: '/Images/ProfilePictures/no-img.png'
}
});
$('form').submit(function () {
var imageData = $('.image-editor').cropit('export');
// imageData containing the Data URI for the cropped image
$('.hidden-image-data').val(imageData);
});
});
</script>
Controller - Register
public async Task<ActionResult> Register([Bind(Exclude = "ProfilePicture")]RegisterViewModel model) {
if (ModelState.IsValid) {
// To convert the user uploaded Photo as Byte Array before save to DB
byte[] imageData = null;
if (Request.Files.Count > 0) {
HttpPostedFileBase poImgFile = Request.Files["ProfilePicture"];
using (var binary = new BinaryReader(poImgFile.InputStream)) {
imageData = binary.ReadBytes(poImgFile.ContentLength);
}
}
.... more code ....
}
}
Feel free to ask for more explanatory details.
A data URI is a non-binary encoding of binary data. That is the data you want.
It's probably base64 encoded so you can just base64 decode it on the server side before you write it.
There's code here to encode into and from base64
Here's the example code from the site linked above:
public class Base64Decoder
{
public static void Main ()
{
string inputText = "This is some text.";
Console.Out.WriteLine ("Input text: {0}", inputText);
byte [] bytesToEncode = Encoding.UTF8.GetBytes (inputText);
string encodedText = Convert.ToBase64String (bytesToEncode);
Console.Out.WriteLine ("Encoded text: {0}", encodedText);
byte [] decodedBytes = Convert.FromBase64String (encodedText);
string decodedText = Encoding.UTF8.GetString (decodedBytes);
Console.Out.WriteLine ("Decoded text: {0}", decodedText);
Console.Out.Write ("Press enter to finish.");
Console.In.ReadLine ();
return;
}
}

Moving the submit button outside the form in MVC 5 with Partial view

In MVC 5,
I have a Dialog for editing.
The Content area is created from a Partial view.
If I have the submit button inside the form in the Partial view it works. But I would like the Save button to be at the button of the Dialog and hence outside the form and Partial view.
The problem is now that the forms data doesn't get posted. How would you fix this?
I have two ideas:
1) Wrap the form outside the Partial view
2) Make a AJAX request and not use the helper, and collect the data from the form somehow? Doesn't feel like the right way.
Dialog:
<div id="myModal" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit database connection</h4>
</div>
<div class="modal-body">
#{ Html.RenderPartial("View"); }
</div>
<div class="modal-footer">
<button id="saveBtnSettings" type="button" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Dialog javascript
var saveSettings = function () {
var url = buildUrl("Edit", "Setting");
$.ajax({
type: "POST",
url: url
})
.done(function (data, textStatus, jqXhr) {
alert('done' + data);
})
.fail(function (jqXhr, textStatus, errorThrown) {
alert(textStatus.toUpperCase() + ": " + errorThrown + 'Could not load html. ');
});
};
Partial view
#using (Ajax.BeginForm("Edit", "Setting", new AjaxOptions { UpdateTargetId = "div" }))
{
<fieldset>
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.User, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.User, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.User, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DataSource, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DataSource, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DataSource, "", new { #class = "text-danger" })
</div>
</div>
</div>
</fieldset>
}
Partial view - Works with button inside of the form
#using (Ajax.BeginForm("Edit", "Setting", new AjaxOptions { UpdateTargetId = "div" }))
{
<fieldset>
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.User, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.User, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.User, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DataSource, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DataSource, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DataSource, "", new { #class = "text-danger" })
</div>
</div>
<p>
<input type="submit" value="Calculate" /> #* WORKS WITH BUTTON INSIDE OF FORM *#
</p>
</div>
</fieldset>
}
You can place a submit button outside the form tags by specifying the form attribute (HTML5 only)
<form .... id="editform">
....
</form>
<input type="submit" form="editform" />
Note if the submit button has a value attribute, it won't be posted back.
Another option may be to use css to position it.
Just submit the form using Javascript:
function SubmitMyForm(){
document.getElementById("myForm").submit();
}
HTML:
<input type="button" value="Calculate" onclick="SubmitMyForm()" />
I think you're looking for: document.myform.submit();
Here is a Fiddle adapted form of code from this page.

How to submit a form inside Razor view by Java Script function WITHOUT redirection?

To submit form below I have to click <input type="submit" value="Save" /> which is at the bottom of form pasted below:
#model WebApplication2.Models.Person
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<input type="submit" value="Save" class="btn btn-success" style="width: 200px; font-weight: bold;" />
</div>
</div>
</div>
}
This causes invoking POST Edit method in PersonController:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,FirstName")] Person person) {
if (ModelState.IsValid) {
db.Entry(person).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
I also would like to have a JavaScript function which does the same( when I invoke this function) but does not redirects me to any view. Just invokes POST Edit and passes contents of the form above.
Question: How to write JavaScript function which submits the form above without redirecting me anywhere?
function SubmitForm() {}
EDIT
I tried this.
The JavaScript method is invoked when I click #Html.ActionLink("Add a Report", "Create", "Reports", new { personId = Model.Id }, new { onclick = "SubmitForm()" }) (alert is displayed) but form is not submited(standard submit button works, so it is JavaScript function fault).
Form:
#using (Html.BeginForm(null, null, FormMethod.Post, new { name="myForm", id = "myForm" })) {
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<p> #Html.ActionLink("Add a Report", "Create", "Reports", new { personId = Model.Id }, new { onclick = "SubmitForm()" })</p>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<input type="submit" value="Save" class="btn btn-success" style="width: 200px; font-weight: bold;" />
</div>
</div>
</div>
}
and the function:
function SubmitForm() {
alert("IS INVOKED");
$("#myForm").submit();
}
Easiest way I have found. :
$("#myForm").submit();
Possible duplicate of. :
ASP.Net MVC, Submit a form using javascript
You also need to name your form. In this instance myFrom is the id of your form. Something like. :
Html.BeginForm(null, null, FormMethod.Get, new { name = "myForm", id = "myForm" })

Categories