Textbox ENTER to save the text to DB -- MVC - asp.net-mvc

I have a text box and if user types something and Hit enter it should save it to the DB.
#Html.TextArea("txtComments", new {#style = "width: 450px;",#placeholder = "Enter Comments here" })
Basically am looking for an event to fire on ENTER. and am implementing in RAZOR MVC.
i saw few ideas of keeping and other stuffs. But i thought this is the better place to post it.
Thanks

Basically am looking for an event to fire on ENTER
You could subscribe to the .keypress() event of the textarea and detect if Enter was pressed:
$(function() {
$('#txtComments').keypress(function() {
var code = e.keyCode ? e.keyCode : e.which;
if(code == 13) {
// Enter was pressed => act accordingly
}
});
});
and am implementing in RAZOR MVC.
Razor is a view engine which runs on the server. You cannot detect key presses on the server. You will have to use client side scripting (javascript) as I have shown previously.

Related

ASP.NET MVC Fill a label at the click of a button

I'm working on an email sending application. I have created a method to receive all emails. My goal now is to create a button of the genre (Select all) and the label for the recipient appear there all the emails contained in the database when I click on the button. My problem is that I do not know where to start nor do I have any examples
Method
[HttpPost]
public JsonResult GetEmails ()
{
ProjectEntities entities = new ProjectEntities ();
var emails = from User in entities.Use
             select User.Email;
return Json(emails);
}
Hi Dário, welcome to stack.
From your question i assume you are working on a Asp.net mvc application where you want to show a button in your view page(Html page) and when this button will be clicked then you will retrieve some data from database(as you already wrote a method for that).
To achieve that first you have to create a button in view. you can write some html code like below
<div id="label_id">
//comment: In this div email address will be shown after getting it from
//server.
</div>
<input type="button" id="btn_submit" value="submit"/>
Now you have to write a click event which will fire when someone click the submit button. It will send a post request using Ajax to server and get back your email address. please check jquery code, do not forget to add jquery link to your view file.
$(document).on('click','#btn_submit', function(){
$.ajax({
type: 'POST',
url: 'Controller/GetEmails',
dataType: 'json',
success: function (data) {
//comment you will find email address from this data object.
//bind data to view.
$('#label_id').html(data);
}
});
});
you can check this
article for better understanding of Asp.net mvc and Ajax

Symfony Form reset after submit

I have a very simple form created with createFormBuilder providing one simple text field only (there is no entity attached to the form).
When the form is submitted I do some logic and then unset form and formData as suggested in many posts to this topic if you want the form to be reset after submitting.
There is some additional action by simple ajax-requests that mainly initiates some UI stuff - not touching the form itself nor reloading the page.
Everything works fine except that the form apparently just doesn't want to be reset - meaning: Whenever the page reload button in the browser is pressed the standard browser dialog appears that asks if you want to submit the form again. And when you do the last value typed in BEFORE the last render call is submitted.
The template kw.html.twig is straight forward - mainly some UI stuff the form rendering and a bit jquery for handling ajax. Nothing special there.
I can't figure out why this is happening - I just want a clean form on any request. Which I thought I get when unsetting thing like in the sample code below.
/**
* #Route("/kw", name="show_kw")
*/
public function showKwAction(Request $request)
{
if($request->isXmlHttpRequest()) {
if( $request->getMethod() == 'POST' ) {
// do some logic...
return $this->json(array('kw_success' => true));
}
}
$kwData = array();
$kwForm = $this->createFormBuilder($kwData)
->add('kd', TextType::class)
->getForm();
if( $request->isMethod('POST') ) {
$kwForm->handleRequest($request);
$formData = $kwForm->getData();
// do some logic with formData...
unset($kwData);
unset($kwForm);
$kwData = array();
$kwForm = $this->createFormBuilder($kwData)
->add('kd', TextType::class)
->getForm();
}
$templateData = array(
'kwForm' => $kwForm->createView()
);
return $this->render(':backend:kw.html.twig', $templateData);
}
Any help is highly appreciated.
EDIT: Using Symfony 3.1
It's exactly what Alsatian said in the comment. Browser is trying to repeat last request.
However I think that instead of destroying this form you can simply redirect to the same route with $this->redirectToRoute once you processed data, of course if it's not a problem.
Also I see you check at least twice if method is post. If it's not colliding with the rest of your application logic you can specify #Method("POST") in annotation so you don't have to check it directly in code anymore.
Best Regards,
R.

ASP.NET MVC handling server side validation on jQuery form wizard/tabs

I'm working on a large form that I'm looking to improve the usability of by sectioning it into a jQuery form wizard (jQuery tabbed panels).
I have already implemented both client-side validation and server-side validation. Client side validation is performed on each tabbed panel before moving to the next tabbed panel and server side validation is only performed once the form is posted to the server.
The thing I'm having trouble with is how to best handle server-side validation errors. Currently if the form is posted to the server it returns the form and shows any errors however this doesn't really work to well with jQuery tabbed panels as the tabbed panel resets to its default state once the form is returned.
If the form fails server side validation how do I reload the form and automatically show the tabbed panel in which the inputs that failed server side validation reside. For example, lets say I have three tabbed panels in my form wizard. If an input in the third tabbed panel failed server side validation how do I reload the form with the third tabbed panel shown.
I have tried creating the from wizard server-side where each section has its own view and controller action however however with this approach it much harder to create a navigation bar to move between the form section.
I had a similar issue and i used following solution:
Post form data via jquery ajax
$("#save").on("click", function (e) {
//clear error if exists before
var $form = $("#saveform");
$.post($form.attr("action"), $form.serialize(), function(result) {
if (result.ok) {
//handle success
} else {
handleError($form, result);
}
});
});
Validate data in the server side and send json result to the client(ok or errors).
if (ModelState.IsValid)
{
return Json(new {ok = true});
}
else
{
return Json(new {ok = false, errors= ModelState.Values.SelectMany(x => x.Errors)});
}
Handle result in client side(if has any error show in the form and activate tab)
function handleError($form, result) {
for (var i = 0; i < result.errors.length; i++) {
var item = result.errors[i];
for (var j = 0; j < item.MemberNames.length; j++) {
var input = $form.find("[name=" + item.MemberNames[j] + "]");
var tab= input.closest(".tab");
tab.addClass("active");
//show error(near the input or in summary)
}
}
}

How to receive Open/Save file dialog after ajax-form post with ASP.NET MVC and jQuery

I want to be able to receive open/save dialog for a pdf file being returned from controller without using 'Html.Beginform' in ASP.NET MVC. I´m using 'Ajax.Beginform' since I can register events to fire OnBegin and OnComplete (which I think I can´t do when using Html.Beginform, or is it?).
I want to state that the problem is not creating and receiving the file from the server when using 'Html.Beginform' because that works fine, but without the events I want to use. I´m using 'Ajax.Beginform' and the file is being returned from the controller but nothing happens after that client side.
My cshtml
#using (Ajax.BeginForm("CreatePdf", "Print", null, new AjaxOptions() { LoadingElementId = "printLoading", OnSuccess = "printPageComplete"}, new { id = "exportForm" }))
{
//Stuff abbreviated
<input type="button" onclick="onPrint()" />
}
My jQuery
function onPrint()
{
//Stuff abbreviated
$("#exportForm").submit();
}
function printPageComplete(result)
{
//this 'result' variable is obviously holding the file from the controller
//stuff abbreviated
//TODO: I need to open file dialog here
}
My Controller
[HttpPost]
public ActionResult CreatePdf(FormCollection collection)
{
//Stuff abbreviated
return File(thePdf, _mimeTypes[ExportFormat.Pdf], "thePdf.pdf")
}
As you can see I´ve managed to get this far as in the printPageComplete function but I´m not sure where to go from here. Should I continue using the ajax form or should I stick with the html form and try to find other way to fire the events I so sorely need to use?
Perhaps I´m going about this all wrong and your help would be very well appreciated.
You can post a form without using Ajax.BeginForm. It is more work, but gives you more flexibility:
$('#exportForm').submit(function (e){
e.preventDefault();
//Do any validation or anything custom
$.ajax({
//set ajax settings
success: function(){
// Handle the success event
}
});
});

Customizing [Success] Messages in Asp.Net MVC

I have found many articles about customizing error messages in asp.net mvc.
What I would like to know is how to show a success message.
For example, when I enter a valid email address I would show that the data entered has passed the validation by either changing the style of the control in which it was entered or providing a successful validation message.
All the asp.net mvc samples I have see so far explain how to display or customize error messages after failing validation.
I would like to know how to show a success message when the validation succeeds.
Does anyone know how to do this or know of a link/resource that can show me how?
Thanks in advance.
You can override the unobtrusive clientside validation setting in asp.net mvc3.
You can see how to do this here
The most important code in from the url is:
$(function() {
var settngs = $.data($('form')[0], 'validator').settings;
var oldErrorFunction = settngs.errorPlacement;
var oldSucessFunction = settngs.success;
settngs.errorPlacement = function (error, inputElement) {
//Do something here
oldErrorFunction(error, inputElement);
}
settngs.success = function (error) {
//Do something here
oldSucessFunction(error);
}
});
Its a good idea to show success message. You can display a success message by applying jquery on view's button click where you are submitting data.

Resources