how to submit a form after jquery dialog - asp.net-mvc-4

I have a mvc4 web application a page with form
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>News</legend>
<div class="editor-label">
#Html.LabelFor(model => model.title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.title)
#Html.ValidationMessageFor(model => model.title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.summery)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.summery)
#Html.ValidationMessageFor(model => model.summery)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
I want after form is valid to call a function that will show a confirm dialog (jquery)
$("#dialog-message").dialog({
modal: true,
resizable: false,
draggable: false,
title: title, closeOnEscape: false,
buttons: {
"OK submit": function () {
},
"Cancel Submit": function () {
}
}
});
what is the best whay to do so ?
I want the form to be validated ,next step if valid to show confirm message ,next step if "OK submit"
pressed to submit the form.

Try this:
$(formSelector).submit(function(){
var frm = $(this);
if (frm.validate()) {
$("#dialog-message").dialog({
buttons: {
"OK submit": function () {
//not sure - here can be a mistake
frm.unbind('submit');
frm.sumbit();
},
"Cancel Submit": function () {
}
}
});
}
return false;
});
If you want to show not a custom dialog you can use this:
$(formSelector).submit(function(){
var frm = $(this);
if (frm.validate()) {
return confirm("Want to submit?");
}
return false;
});

Related

Auto Adjust height of multiline editor for in MVC using bootstrap

I have below editorfor which is multiline, I need to auto adjust height when user starts adding multiple email address in separate lines using bootstrap. Any code example is highly appreciated.
Model:
[DataType(DataType.MultilineText)]
public string AdditionalEmailAddressesText { get; set; }
View:
<div class="form-group">
#Html.LabelFor(m => m.AdditionalEmailAddressesText, new { #class = "col-sm-2 control-label" })
<div class="col-sm-10">
#Html.EditorFor(m => m.AdditionalEmailAddressesText, new { htmlAttributes = new { #class = "form-control", placeholder = #Strings.Porting_AdditionalEmailAddressesSubtext } })
#Html.ValidationMessageFor(m => m.AdditionalEmailAddressesText)
</div>
</div>
For textarea tag, there's no auto-height attribute to make it adjust the height automatically. And for the [DataType(DataType.MultilineText)] annotation, it doesn't provide feature for setting rows and colums as well. So you have to write script code to add oninput event listener to change the style.
#model NewEvent
<h1>#ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>
<div class="form-group">
#Html.LabelFor(m => m.Body, new { #class = "col-sm-2 control-label" })
<div class="col-sm-10">
#Html.EditorFor(m => m.Body, new { htmlAttributes = new { #class = "form-control", placeholder = "placeholder" } })
#Html.TextAreaFor(model => model.Body, new {cols = 2, rows = 5})
#Html.ValidationMessageFor(m => m.Body)
</div>
</div>
#section scripts {
<script>
$("#Body").each(function () {
this.setAttribute("style", "height:" + (this.scrollHeight) + "px;overflow-y:hidden;");
}).on("input", function () {
this.style.height = "auto";
this.style.height = (this.scrollHeight) + "px";
});
</script>
}

Triggering sweet alert message from the code behind for create method

Thanks to the excellent answer by Rena in the previous question I am also asking how do I achieve the same effect of the sweet alert message box on the create controller action I tried with the code they gave in this.
Using JavaScript code behind asp.net core c#
But because the action create submits the form first it doesn't seem to like the trigger the alert.
swal({
title: "MIS",
text: "Case Created your Case Number is ",
icon: "warning",
buttons: true,
dangerMode: true,
})
just post the form with ajax after that jsut show the message you want
<form action="/your action url" method="post" id="formCreate">
...Yıur item inputs
<button type="submit"></button>
</form>
$("#formCreate").submit(function (event) {
event.preventDefault(); //prevent default action
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
url: post_url,
type: request_method,
data: form_data
}).done(function (response) { //
Swal.fire({
position: 'center',
icon: "warning",
text: "Case Created your Case Number is "+response.Id,
title: "MIS",
showConfirmButton: false,
timer: 1500,
}).then(() => {
window.location.reload(true);
})
});
});
in cotroller side you should return something like this
[HttpPost]
public IActionResult Create(Item item){
//create item
return Json(new {Id=item.id});
}
It seems you want to trigger the sweet alert when you click the submit button.
Here is a working demo:
Model:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
}
Index.cshtml:
#model IEnumerable<Test>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Create.cshtml:
#model Test
<h1>Create</h1>
<h4>Test</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="button" onclick="Create()" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
<script>
function Create() {
swal({
title: "MIS",
text: "Case Created your Case Number is " + $("#Name").val(),
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willCreate) => {
if (willCreate) {
var data = $('form').serialize();
$.ajax({
url: "/tests/create",
type: "POST",
data: data,
dataType: "html",
success: function () {
swal("Done!", "It was succesfully created!", "success")
.then((success) => {
window.location.href="/tests/index"
});
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error creating!", "Please try again", "error");
}
});
}
});
}
</script>
}
Controller:
public class TestsController : Controller
{
private readonly Mvc3_1Context _context;
public TestsController(Mvc3_1Context context)
{
_context = context;
}
// GET: Tests
public async Task<IActionResult> Index()
{
return View(await _context.Test.ToListAsync());
}
// GET: Tests/Create
public IActionResult Create()
{
return View();
}
// POST: Tests/Create
[HttpPost]
public async Task<IActionResult> Create(Test test)
{
if (ModelState.IsValid)
{
_context.Add(test);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(test);
}
}
Result:

File upload in MVC 5 when used in bootstrap modal returns null

I'm trying to allow file uploading on modal popup using bootstrap modal popup.
But it always returns null for type = "file"
I've tried following solutions but no luck:
File upload in MVC when used in bootstrap modal returns null
it always return null. If I run this directly as separate page then it works fine but only having problem with popup.
I tried to change the content type on ajax but then its giving me this error "required anti-forgery form field __requestverificationtoken is not present"
I've tested what does page post using development tools:
enter image description here
here are my codes:
controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Create([Bind(Include = "ID,FileName,Link,SourceType,Comments,SourceDate,DateCreated,DateModified,ProjectID")] ProjectSource projectSource, HttpPostedFileBase uploadFile)
{
if (ModelState.IsValid)
{
//upload method 1
var fileSavePath = "";
if (HttpContext.Request.Files.AllKeys.Any())
{
// Get the uploaded image from the Files collection
var httpPostedFile = HttpContext.Request.Files[0];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
// Get the complete file path
fileSavePath = (HttpContext.Server.MapPath("~/xyz/") + httpPostedFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
}
//upload method 2
if (uploadFile != null && uploadFile.ContentLength > 0)
{
try
{
string path = Path.Combine(Server.MapPath("~/xyz/"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
}
else
{
ViewBag.Message = "You have not specified a file.";
}
db.ProjectSources.Add(projectSource);
await db.SaveChangesAsync();
return " File : " + ViewBag.Message + " == " + fileSavePath;
}
return " File : " + ViewBag.Message +" === "+sb.ToString();
}
view:
#model CharterPortal.Models.ProjectSource
#{
Layout = "";
#Scripts.Render("~/Scripts/jquery-2.2.3.min.js")
#Scripts.Render("~/Scripts/moment.min.js")
#Scripts.Render("~/Scripts/bootstrap.min.js")
#Scripts.Render("~/Scripts/bootstrap-datetimepicker.min.js")
#Scripts.Render("~/Scripts/bootstrap.fd.js")
}
×
Add new Source
#using (Html.BeginForm("Create", "ProjectSource", FormMethod.Post, new { enctype = "multipart/form-data" , #id="ajaxForm"}))
{
#Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
#*#Html.ValidationSummary(true, "", new { #class = "text-danger" })*#
<div class="form-group">
#Html.Label("Source file", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.FileName, new { htmlAttributes = new { #class = "form-control" } })
#*<input type="file" name="uploadFile" />*#
#Html.TextBox("uploadFile",null, new { #class = "form-control", type = "file" })
#*Add file*#
#Html.ValidationMessageFor(model => model.FileName, "", new { #class = "text-danger" })
</div>
</div>
#*<div class="form-group">
<div class="col-md-10" id="files" style="padding-left:40px;">
</div>
</div>*#
<div class="form-group">
#Html.LabelFor(model => model.Link, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.Link, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Link, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SourceType, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.SourceType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SourceType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Comments, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6" style="color:black;">
#Html.TextAreaFor(model => model.Comments, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SourceDate, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6" style="color:black;">
#Html.EditorFor(model => model.SourceDate, new { htmlAttributes = new { #class = "form-control datepicker datefield" } })
#Html.ValidationMessageFor(model => model.SourceDate, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-med btn-orange" data-dismiss="modal">Cancel</button>
<input class="btn btn-med btn-orange" type="submit" name="submit" value="Add" />
</div>
}
ajax:
$('form', dialog).submit(function (event) {
event.preventDefault();
$.ajax({
url: this.action,
type: this.method,
async: true,
data: $(this).serialize(),
contentType:this.enctype,
success: function (result) {
if (result) {
alert(result)
//Refresh
} else {
alert(result)
}
}
});
return false;
});
I hope to get good working solution for this:
thanks in advance for your time.
Thanks
Ive been using this block of code to solve this problem and ModelState.IsValid in partials for about a year. cheers.
$(function () {
window.addEventListener("submit", function (e) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
if (form.dataset.ajaxUpdate) {
var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
if (updateTarget) {
updateTarget.innerHTML = xhr.responseText;
}
}
}
};
xhr.send(new FormData(form));
}
}
}, true);
$('#modal').on('shown.bs.modal', function () {
$.validator.unobtrusive.parse($(this));
});
$('#modal').on('hidden.bs.modal', function () {
$('#spinner').remove();
});
$.ajaxSetup({ cache: false });
});

Recaptcha doesn't work with ajax and partial views

I'm using Recaptcha in my MVC4 web app. It was working correctly when it was embedded in the form but when I moved the #Html.Raw(Html.GenerateCaptchaHelper()) to partial view and trying to call this partial view via ajax request, it doesn't work!
Extension code :
public static string GenerateCaptchaHelper(this HtmlHelper helper)
{
var captchaControl = new Recaptcha.RecaptchaControl
{
ID = "recaptcha",
Theme = "clean",
PublicKey = ************,
PrivateKey = **********************,
Language = "En"
};
var htmlWriter = new HtmlTextWriter(new StringWriter());
captchaControl.RenderControl(htmlWriter);
return htmlWriter.InnerWriter.ToString();
}
my partial view is has the code like :
<p>#Html.Raw(Html.GenerateCaptchaHelper())</p>
and inside my controller
public PartialViewResult Captcha()
{
return PartialView();
}
and inside my main view:
#using (Html.BeginForm("Login", "Account", new { returnUrl = ViewData["ReturnUrl"] }, FormMethod.Post,null))
{
#Html.AntiForgeryToken()
<form role="form">
<div class="form-group">
<label>#Html.LabelFor(m => m.Email)</label><br />
#Html.TextBoxFor(m => m.Email, null, new { #class = "form-control", autocomplete = "off" })
</div>
<div class="form-group">
<label>#Html.LabelFor(m => m.Password)</label><br />
#Html.PasswordFor(m => m.Password, new { #class = "form-control", autocomplete = "off" })
</div>
<div id="captchaView" class="form-group">
</div>
<button type="submit">Login</button>
</div>
</div>
</form>
}
and the javascript is :
$.ajax({
url: '/Account/Captcha',
type: 'GET',
success: function(data) {
$('#captchaView').html(data);
}
});
Could you please help me to figure out why?

passing value via ajax to controller action having null httppostedbasefile

My Razor html:
#using (Html.BeginForm("CreateTestinomialPage", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Fill Form</legend>
#Html.HiddenFor(m => m.PostedTypeId)
<div class="editor-label">
#Html.DisplayName("Image Upload")
</div>
<div class="editor-field" >
#*<input type="file" name="file" id="file" />*#
#Html.TextBoxFor(m => m.file,new{type="file"})
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Message)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.Message)
#Html.ValidationMessageFor(model => model.Message)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Postedby)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Postedby)
#Html.ValidationMessageFor(model => model.Postedby)
</div>
<p>
<input type="submit" value="Create" />
</p>
<div id="result"></div>
</fieldset>
}
My scripts:
<script type="text/javascript">
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
},
complete: function () {
$('form').each(function () {
this.reset(); //Here form fields will be cleared.
});
},
});
}
return false;
});
});
</script>
my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateTestinomialPage(TestinomialsModels models,HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file == null)
{
ModelState.AddModelError("File", "Please Upload Your file");
}
else if (file.ContentLength > 0)
{
int maxcontentlength = 1024 * 1024 * 3;
string[] AllowedExtension = new string[] { ".jpg", ".gif", ".png" };
if (!AllowedExtension.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedExtension));
}
else if (file.ContentLength > maxcontentlength)
{
ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + maxcontentlength + " MB");
}
else
{
var filename = Path.GetFileName(models.file.FileName);
models.ImagePath = ConfigurationManager.AppSettings["ImagesavePath"].ToString() + filename;
postservices.AddTestinomailPost(models);
var path = Path.Combine(Server.MapPath("~/Content/Upload/Images"), filename);
models.file.SaveAs(path);
return Content("Successfully Submiited");
}
}
}
return Content("An error occur while saved Plese try again..");
}
There is controllerAction null httppostedbasefile..