Load JavaScript model from fields on page - javascript

I learned some good things here here
What I want to know if it is possible to load these various JS model values, once the model is converted, from fields on the page without having to use
model.ProductId = $("#txtProductId").val();
What I mean, and this may be a dumb question, is there a way to type in data directly into the JS field? Like the #Html.TextBoxFor to load controller model field for JS variable?
My product form looks somewhat like this:
#model ProductModel
<form id="productForm">
<table>
<tr>
<td>#Html.TextBoxFor(o => o.BrandName, new {#id=txtBrandName})
///etc

One option you have is to use a javascript MVC framework like AngularJS, and then this will happen (more or less) automatically for you. You will probably want to create the text input using plain HTML instead of #Html.TextBoxFor.
For example, if you use AngularJS, your view would look like:
<input type="text" ng-model="model.ProductId" />
This creates a two-way data binding between your text box value and model.ProductId. What this means is that any time the user types a value into the text box, model.ProductId will automatically be set to the new value. Also any time you set model.ProductId in javascript, your text box will automatically update.
As a note, if you have any repeat sections in your view using #for loops, you will probably want to convert them to ng-repeat sections (for AngularJS at least).

I've found the best way to do this with a lot of help from Stephen Muecke. What I do is in the main page I have several DIVs:
<div id="divPerson" style="display: none"></div>
<div id="divProduct" style="display: none"></div>
In the JavaScript code I load each DIV with a partial view:
function loadPerson() {
$.ajax({
type: 'POST',
url: '#Url.Action("LoadPerson"),
success: function(data) {
$("#divPerson").html(data);
$("#divPerson").show();
}
});
And the controller method:
public ActionResult LoadPerson()
{
var model = new PersonModel();
return PartialView("PersonPage", model);
}
And in the PersonPage:
$(document).ready(function() {
$.validator.unobtrusice.parse();
});
And each field in this page has a class of 'personForm'.
This is to read the validation tags again after the page has loaded so that clicking next is this in the main page:
function goNext() {
if (!$("#form1").valid()) {
return false;
}
$.ajax({
type: 'POST',
url: '#Url.Action("AddPerson),
data: $(".personForm").serializeArray(),
success: function(data) {
$("#divProduct").html(data);
$("#divProduct").show();
$("#divPerson").hide();
}
});
I do the same thing for the product page by setting a certain class and serializing those controls to send to the controller.
This, to me, is a good balance between using MVC and jQuery to make the page smooth, crisp, and clean, and enhance the user experience.

Related

Getting the value of an input field, which gets dynamically placed (not via js) onclick

I spent a few hours searching and trying stuff out, but I can't get my ajax form submit working. (I'm also really not a front-end person, so sorry if I mess up my explanation)
I have a site that dynamically inserts HTML content (through JSP, not javascript). I have a simple form with a submit button inside that inserted html. This is the piece of html I have:
<tr>
<td>Change stock by:</td>
<td>
<div id="quantityinput" class="field has-addons">
<div class="control"> <input class="input" type="text" id="mutation" placeholder="0">
</div>
update
</div>
</td>
</tr>
I managed to link the button to the right ajax-function, like this:
(.editor__product is the direct parent of the form, but there is a bunch of non-form information there)
$(".editor__product").on("click", "#quantityConfirm", function ($) {
$.ajax({
method: "POST",
url: '/bullet-journal/mutateitem',
data: {
product_id: product_id,
product_mutate: product_mutate
}
})
.done(function (html) {
$('#main').load(document.URL + ' #main');
$(".editor__product").load('${pageContext.request.contextPath}/refreshinfo');
});
});
But the problem is, I have no idea how to get the value from my "#mutation" input field. I tried various ways to append it to my document and get it, but it either results in a new text field somewhere on the bottom of my page, or simply in a NULL value error. I have more ajax forms in the website which work fine, but they use elements that are hardcoded.
Every solution I could find was specifically for javascript-generated content, while my input doesn't get generated by javascript.
How would I go about extracting the value from my mutation input? Thanks a lot for any advice, the browser console isn't very helpful.
Get the value using js :
var mutation = document.getElementById('mutation').value;
or with jquery
var mutation = $('#mutation').val();
And pass mutation in your data or do what you need to with it

Reload part of HTML without refreshing page?

When clicking on an button icon:
<a onclick="updateFav({{v.video_id}}, {{v.favorite}});" ><span class="myicons {% if v.favorite == 1 %} heart_active{% else %} heart {% endif %} "></span></a>
I'm using this to change data in my sql database
function updateFav(video_id, favorite) {
$.ajax({
type: "POST",
url: '{{baseurl}}/fav.php',
data:{id:video_id, fav:favorite},
});
}
Depending on database data (0 or 1) heart icon will be gray or red. Clicking on icon works and after refreshing page the changes are visible.
How can I refresh a certain html element? A div for example.
Basically: Have the same effect as the 'star' favorite button on this page (stackoverflow).
To reload a part of a page without refreshing the whole page simply use an ajax request to fetch new data and add it to the div or any element you want see the code below for an example:
$.ajax({
type: "GET",
url: 'getnewData.php',
success:function(response){
$('#myElement').html(response);
},
});
What we did here is we issued an ajax request in which we requested data from getnewData.php and placed the data (which came to us in the response variable) and then we placed the data in the div with an id = myElement
You can go all the way and use a reactive framework or just create a function to update the current element after updateing the database.
When selecting with jQuery $('') or with plain js document.querySelector(), you get a living reference to the DOM element. So you can add/toggle/remove an "active class" to it to styled it as filled with css.
Tricky part here is that you have to keep consistency between the view and the model with your own code. Reactive frameworks or two-way data binding do it for you.

Can a Drop Down List Trigger A Partial View To Update on A Create View Form In mvc? [duplicate]

This question already has answers here:
Partial Views on mvc create view that use a dropdown list to populate the partial view's view bag is this possible in mvc?
(2 answers)
Closed 6 years ago.
The option I am trying to apply to a create view form is one on which the user selects an item from the drop down list on a create from before a record is written to the database and as they select their records from the dropdown list on the create view form a partial view that is hidden on this form becomes visible and shows values that are in a viewbag.
As I have seeked help for this before I don't this the question was clear on what the goal was and that this is on the create which may prevent from happening as this may be a limitation within the mvc methods since mvc is for phones small devices. I am building this application on a full pc. Some say it can be done. I am using viewbag as that is the only thing I understand.. I don't understand the model concept and I don't know what ajax is or how to use. I just know how to do the javascripting functions as I have seen examples w3schools.
What I have so far,
I have something similar to this for my partial view: Called _IssuesListPartial
<table cellpadding="1" border="1">
<tr>
<th>
Issues List
</th>
</tr>
#foreach (SystemX.Models.VUE_ISSUE_LIST_FULL item in ViewBag.IssuesList)
{
<tr>
<td>
#item.ISSUE_DISCRIPTION
</td>
</tr>
}
</table>
In my crated Controller code behind I have under the create option a few items
I have a function that makes a list for the view bag.
private List<VUE_ISSUE_LIST_FULL> Get_IssuesList(int? VID)
{
return db.VUE_ISSUE_LIST_FULL.Where(i => i.ID == VID).ToList();
}
I then assign the results to the view bag in another function that starts with the words action results. Its called UpdateIssuesList:
This is under the create logic in the controller.I saw something similar they had a [HttpPost] but I get an error when the create form is trying to render so I changed it to [HttpGet] it works and the create for loads. I am not sure that the [HttpGet] or [HttpPost] does..I just know that the create forms loads with [HttpGet]
So in the controller under the create functions I have this. Please keep in mind I have all of the other stuff that the scaffold builder made for the create view. I just added this code behind under it.
[HttpGet]
public ActionResult UpdateIssuesList(int? VID)
{
ViewBag.IssuesList = Get_IssuesList(VID);
return PartialView("_IssuesListPartial",ViewBag.IssuesList);
}
In the create form view I have as few items... The area on the form where I would like this list to show when it is made visible:
under function public ActionResult Create I have:
public ActionResult Create(int RES_ID, FormCollection Collection, [Bind(Include = "R.... and so on...
UpdateIssuesList(int.Parse(Collection["RES_ID"]));
and under the public ActionResult Create()I have:
the function call to the UpdateIssuesList funtion.. I just send a random value that will build a blank list.
UpdateIssuesList(808);
Also
This is the code behind for the create view form where I want to render the partial view:
<div class="col-sm-6">
<div class="form-horizontal" style="display:none" id="PV_IssueList">
#{ Html.RenderAction("UpdateIssuesList",new {#VID = 1 });}
</div>
</div>
And I also have in the script section of the create view form the code behind that run when the user makes a change to the drop down list on the create view form. The end goal again is when the user click and changes the item on the dropdown list... the value gets id values gets sent to the list maker and and generates a new last and that new list is passed to the partial view and the form is updated.
$(document).ready(function () {
$('#RES_ID').change(function ()
{
debugger;
$("#PV_IssueList").show(); // Shows List
$.post("/Create/_IssuesListPartial?VID=1")
});
})
is it possible for mvc to update a create from as there is nothing there ? No code or event trigger that will refreshes the partial view before the form is submitted So This may not be possible with mvc and I am wasting my time trying. I have just smashed together peoples Ideas that I have seen as I have not seen an actual example of a list being rendered in the create view so I way be chasing windmills here. Thanks for taking time to read this.
So when I run this code I get on the page after I selected a value the head text of the partial view but on list data. When I step through I get data in the variables and stuff but not on screen in the create view form
Ok for some reason the answer was deleted so I will try to answer it differently. The way I got this to work was first with the help of user on this form and other forms as well along with some research. Using the ajax language was a big help as suggested.
Here is the Ajax code behind:
$(document).ready(function () {
$('#RES_VID').change(function ()
{
debugger;
$.ajax(
{
url: '#Url.Action("UpdatePartialViewList")',
type: 'GET',
data: { VID: $('#RES_VID').val() },
success: function (partialView)
{
$('#PV_WidgetList').html(partialView);
$('#PV_WidgetList').show();
}
});
So to break down whats going on here is that I have in my controller a function called UpdatePartialViewList this function passes back a partial view along with its view bag:
The Function in the controller is this:
[HttpGet]
public ActionResult UpdatePartialViewList(int? VID)
{
ViewBag.AList = Get_List(VID);
return PartialView("_WidgetListPartial",ViewBag.AList);
}
So with these two items you have like a place holder it seems. because this will pass the information back to the page. So in my create view I have this:
UpdatePartialViewList(int.Parse(Collection["RES_VID"]));
On Your Create View Screen where you want your partial view to display
<div class="col-sm-6">
<div class="form-horizontal" style="display:none" id="PV_WidgetList">
#{ Html.RenderAction("UpdatePartialViewList");}
</div>
</div>
Hopefully this help other that are use to webforms and are trying to get the whole mvc thing. Best wishes!

JavaScript/Ajax to Dynamically Update WTForms Select Field

OK. I know this has been tackled many times but I can't find an answer with a useful example of javascript to use.
Say I have this form:
class MyForm(Form):
category = SelectField("Category")
issue = SelectField("Issue")
What I need is for whatever is selected in 'category' at runtime to determine what the user sees in the issue dropdown without a POST of any kind ocurring. I know how to dynamically create the choices in the view from my database query. I even have gone so far as to create a dictionary of "issue choices" based off of category choices.
I just can't for the life of me figure out the javascript I need so that on select of something from the category drop down determines whats in the issue dropdown.
I found the info I needed by looking at the example at Flask jQuery AJAX Example -
- it is a minimal working example, almost a
GIST or a book chapter.
I came up with an example very close to jsbueno's implementation. You can find the Gist here. The .py file is a standalone example.
In your html template use jquery to register an ajax request when you click the select field. If the request is a success the html for the select field gets updated with the new select options (send as a response from the server). Look at the actual HTML generated by the template to see how the select field looks like.
<form action="" method="post" id="selectDevice" name="device">
Nummber of Devices: {{ form.selectAmount(size=1) }}
Select device: {{form.deviceAddress() }}
</form>
<script type="text/javascript" charset="utf-8">
$("#deviceAddress").click(function(){
$.ajax({
url: '/selectform',
type: 'POST',
data: $('#selectDevice').serialize(),
success: function(selectOptions){
$("#deviceAddress").empty();
for (var i = 0; i < selectOptions.length; i++){
$("#deviceAddress").append(
$("<option></option>")
.attr("value", selectOptions[i][0])
.text(selectOptions[i][1])
);
}
}
});
});
</script>
On the server side, use a route for the ajax post request.`As example this route changes the options depending on another form field (the information got send over with the data tag in the ajax request). In WTForms the select field options is a list of tuples containing an ID and name, I kept this the same on the python side.
#app.route('/selectform', methods=['POST'])
def updateselect():
deviceAmount = int(request.form.get('selectAmount'))
choices = [('device{}'.format(i), i) for i in range(deviceAmount)]
response = make_response(json.dumps(choices))
response.content_type = 'application/jsons'
return response`
Only one remark: the ajax request is performed on dropping down and on collapsing. The last part is not necessary of course, there is probably a way to structure the jquery so it only requests on dropdown.

Dojo form with ajax/dynamic elements

I am working on a DOJO form, and looking to create the base for basic ajax elements.
It will be a multi-tabbed form - with the dynamic fields being created/populated through ajax.
Is there an easier way of making the form more object orientated - where perhaps if a dynamic field is expected to appear under a parent - the api url is part of a data attribute of that field? What is the best practice for dyanmic forms like this.
http://jsfiddle.net/aGCFs/297/
on(dom.byId("getJson"), "click", function (e) {
dojo.xhrGet({
url: "https://api.github.com/users/mralexgray/repos",
handleAs: "json",
load: function (newContent) {
console.info("JSON loaded from server: ", newContent);
},
error: function () {}
});
console.log("getJson button was clicked!");
});
My latest code is here - http://jsfiddle.net/aGCFs/312/
I am using a dojo.place to dynanmically add a dropdown html markup - as the site is likely to pick up the markup for a prepopulated drop downs from transforming xml to html - my remaining issue now though is how do I invoke the select box generated dynamically?
dojo.place('<select data-dojo-type="dijit/form/Select"><option>test1</option><option>test2</option></select>', "div1", "");

Categories