How to reset a form after submission using Controller As syntax - javascript

After adding an object via a form, I would like to reset the form so the user can add another. I've tried $setPristine() but can't figure out the syntax. As of now, I have just set the location path back to the same page, but that of course doesn't reset anything. Also wondering if $setPristine is the correct way. Here is my save function.
export class AddCarController {
public newCar;
public save() {
this.carService.save(this.newCar).then(() => { this.$location.path('/addCarPage') });
}
constructor(
private carService: MyApp.Services.CarService,
private $location: angular.ILocationService
) { }
}

In angular Your can create model in just in html and also in controller or on both places
If you have created Model in html
$scope.newCar = {} //this will empty whole ui model object
If you have created Model In Javascript Controller
$scope.newCar = new carModel() //this will create new car object with default values , if you have model in controller
Navigate Back And Forth - Not Recommended

Related

originalModel/object always updating even after variable Initialization

hello currently I am trying to populate a default model for originalModel to store the original values. the issue i'm running into is this originalModel keeps updating even after I initialized it and i have no idea why here is the only time I initialize value.
export abstract class RequestBaseComponent{
protected abstract get model(): FaspRequest; //the subClass populates this via Input()
originalModel: FaspRequest;
constructor( private formBuilder: FormBuilder
) {
}
ngOnInit() {
this.originalModel = this.model;
this.setupForm();
}
}
Maybe this is a reference issue. When you do this.originalModel = this.model; , you are actually storing the reference of this.model in this.originalModel. So when this.model is updated, this.orginalModel will be updated.
try this
this.originalModel = JSON.parse(JSON.stringify(this.model));

How to initialize injected form-backing model bean?

So I have model entity Place that has to have initialized some relations.
Now I am using autocreated model form-backing bean in controller as follows:
#GetMapping(value = "/add")
public String addPlacePage(final Place place, Model model) {
model.addAttribute("services", serviceRepository.findAll())
.addAttribute("categories", categoryRepository.findAll())
.addAttribute("cities", cityRepository.findAll());
return "admin/place/addPlace";
}
Place place is created my Spring (Spring-MVC probably). Is there a way to provide a factory method for backing bean? I would like to not to do this in controller.
I have tried to put factory code in my configuration like this:
#Bean
#Scope(value = "prototype")
public Place place() {
log.info("Creating place in FACTORY");
Place place = EntityFactory.emptyPlace();
return place;
}
but this does not work.
So I have ask the same question in #spring channel on freenode, and this is something that came up thanks to user <#_ollie>. In order to do what I want, #ModelAttribute method should be defined in controller like this:
#ModelAttribute
private Place emptyPlace(){
log.info("Creating place in FACTORY");
Place place = EntityFactory.emptyPlace();
return place;
}
and related docs are here
https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-modelattrib-methods

Submitting Ajax form but nothing sent to controller?

I am using the following viewModel on my view:
public class CourseViewModel
{
public IEnumerable<Course_page> Course_page { get; set; }
public IEnumerable<course_section> Course_section { get; set; }
public IEnumerable<course_subsection> Course_subsection { get; set; }
public IEnumerable<Enrollment> Enrollments { get; set; }
}
In my view I have the following ajax form:
#using (Ajax.BeginForm("updateprogress", "User", new { EnrollmentID = Model.Enrollments.Single().EnrollmentID }, new AjaxOptions
{
HttpMethod = "POST",
}, new { id = "ajaxForm" }))
{
#Html.HiddenFor(Model => Model.Enrollments.Single().progress1, new { id = "scenecheck" })
}
I have an animation generated by a program called Hype, within the animation are scenes and the current scene number is called using a javascript function with the value populating the form above in the 'progress1' field:
function updateprogress(hypeDocument, element, event) {
var scenenumber = hypeDocument.currentSceneName();
hypeDocument.getElementById('scenecheck').value = scenenumber;
$('form#ajaxForm').submit();
}
I have some other javascript which listens for the scene change and calls the function above whenever it does change.
When I change HiddenFor to TexboxFor on the page I can see that everything is working correctly within the view, the scene number is present in the textbox.
My controller action when this form submits is as follows:
[Authorize]
[HttpPost]
public ActionResult updateprogress(int EnrollmentID, CourseViewModel model)
{
Enrollment enrollment = db.enrollment.Find(EnrollmentID);
Mapper.Map(model, enrollment);
db.SaveChanges();
return null;
}
I'm using Automapper to map the change to the viewmodel back to the actual model, only a single field is to change in the viewmodel. This might not be the ideal way to do it, I'm still trying to work out how I should approach this.
My two issues are:
1 - The form does not appear to pass anything back to the controller when it submits. So the 'model' object is empty, null. This leads me to believe that what I thought I understood about what I was doing was wrong. Why is the updated field not being passed back to the controller?
2 - Is this the best method for updating the value of a single field in the viewmodel?
Thanks
You have a very complex model, the internal model binder is not going to know what to do with it because you have an IEnumerable of an object and you're editing(or hiding in this case) progress1 of the first Enrollment. You'll have to create a custom model binder.
What's happening on the view is it's storing this input tag of progress1 but when the controller gets it, it's not going to have any idea which Enrollment object it belongs to.
Try just passing in the first Enrollment to your view for editing.

Vaadin Elements get input value of Paper-Input

I've incorporated the Elements add-on for Vaadin into my project and I've got a simple login setup that has two input fields and a button. However, I'm running into a roadblock in how to get the value of the input fields when a user clicks the submit button.
My eventlistener on submit is simple:
button.addEventListener("click", args -> submitLogin());
where the submitLogin() attempts to get the values and pass them to a controller.
controller.submit(username.getValue(), password.getValue());
However, no method I have tried actually returns a non-null value. Any ideas?
Code for paper-input interface:
#Tag("paper-input")
#Import("VAADIN/bower_components/paper-input/paper-input.html")
public interface PaperInput extends Element {
public static PaperInput create(String caption) {
PaperInput input = create();
input.setLabel(caption);
return input;
}
public static PaperInput create() {
return Elements.create(PaperInput.class);
}
}
which references the paper-input html here
and is used simply by calling create(), like so:
PaperInput usernameInput = PaperInput.create();
The PaperButton is created identically but references the paper-button in #iimport and #Tag.
The client side must bind the value to the change. There are two examples in the Lab:
In case you create your element directly:
input.bindAttribute("value", "change")
Or with the interface approach (which you seem to use):
public void setValue(String value)
#UpdatedBy("change")
public String getValue()
Disclainer: I only tried it with a Groovy DSL around elements.

Load Partial View on ajax success method in MVC 4

Problem Statement:View not able to load on ajax success method.
Description:
I'm having couple of dropdowns as cascaded(second binding based on the value of first).
On change of the first dropdown I'm binding second dropdown and again on change of the second dropdown,now on right side I want to display a list of record based on the two dropdown values.
For this,I'm using the following JS code in onchange event for the dropdown 2:
function ShowDocsList() {
var teamId = $('#TeamID').val();
var projectId = $("#ProjectID").val();
var Url = "#Url.Content("~/DocsHome/DocsList")";
$.ajax({
url: Url,
type:'POST',
dataType: 'html',
data: { TeamID: teamId ,ProjectID : projectId},
success: function (data) {
return data;
$('.docs-detail').html(data);
}
});
Here,in DocsHome Controller,DocsList method is getting hit on change of second dropdown which is project dropdown.But the view is not getting rendered .Following is my Controller Code:
public ActionResult DocsList(int teamId, int projectId)
{
List<CustomerViewModel> customerViewsModels = SmartAdminHelper.GetCustomers(db1);
if (Request.IsAjaxRequest())
return PartialView("DocsList");
else
return View("DocsList");
}
Again ,I'm getting record in List but while debugging it does not pass to the DocsList view which according to me is correct.
Here DocsList is the view I want to render as a partial view on change of the second dropdown.
According to my knowledge,while debugging it comes to the point return PartialView("DocsList") but then again it goes back to the ajax success method and finally I find that there I'm doing something wrong.
Earlier I have Json to get data but here I'm calling actionmethod from ajax. So, not sure that also might be a problem as I'm new to this.
What and where exactly I'm doing wrong?
Saroj, I see that this is an old question and that you needed to get it done quickly, but if you happend to come back to this, I'll add my two cents. You need to remove the return statement that David and Ehsan mention above. The rest of the callback function does what it should. In your action method it doesn't look like you're doing anything with the parameters you pass in. I'm assuming that you are going to figure that out after you get the view down to the client. So, lets get that view down to the client.
I like to pass the rendered partial view back to the client as a string of HTML. I do this using a method that I keep in a controller base class that each of my controllers inherit from. To use the method you will need to reference System.Web.Mvc and System.IO namespaces.
The method looks like this:
private string RenderViewToString( string viewName, object model ) {
ViewData.Model = model;
using ( var sw = new StringWriter() ) {
var viewResult = ViewEngines.Engines.FindPartialView( ControllerContext, viewName );
var viewContext = new ViewContext( ControllerContext, viewResult.View, ViewData, TempData, sw );
viewResult.View.Render( viewContext, sw );
viewResult.ViewEngine.ReleaseView( ControllerContext, viewResult.View );
return sw.GetStringBuilder().ToString();
}
}
You pass your model and the name of the view to the method and it returns the rendered view HTML as a string which you can return to the client as a ContentResult.
Update your action method like so:
public ActionResult DocsList(int teamId, int projectId)
{
List<CustomerViewModel> customerViewsModels = SmartAdminHelper.GetCustomers(db1);
if (Request.IsAjaxRequest())
var viewContents = RenderViewToString("DocsList", customerViewsModels);
return Content(viewContents);
else
return View("DocsList");
}
Assuming that the element that you want the rendered view to appear in has the css class '.docs-detail' on it you'll be in business. Hope this helps!

Categories