knockout.js modal binding value update - data-binding

I have the following code in this jsFiddle.
The problem I'm having is that my child items do not update properly.
I can Click "Edit User" with a problem and see the data changing, but when I attempt to add a note or even if I were to write an edit note function, the data does not bind properly
http://jsfiddle.net/jkuGU/10/
<ul data-bind="foreach: Users">
<li>
<span data-bind="text: Name"></span>
<div data-bind="foreach: notes">
<span data-bind="text: text"></span>
Edit Note
</div>
Add Note
Edit user
</li>
</ul>
<div id="userModal" data-bind="with: EditingUser" class="fade hjde modal">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>
Editing user</h3>
</div>
<div class="modal-body">
<label>
Name:</label>
<input type="text" data-bind="value: Name, valueUpdate: 'afterkeydown'" />
</div>
<div class="modal-footer">
Save changes
</div>
</div>
<div id="addJobNoteModal" data-bind="with: detailedNote" class="fade hjde modal">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>
Editing Note</h3>
</div>
<div class="modal-body">
<label>
Text:</label>
<input type="text" data-bind="value: text, valueUpdate: 'afterkeydown'" />
</div>
<div class="modal-footer">
Save changes
</div>
</div>
​
function Note(text) {
this.text = text;
}
var User = function(name) {
var self = this;
self.Name = ko.observable(name);
this.notes = ko.observableArray([]);
}
var ViewModel = function() {
var self = this;
self.Users = ko.observableArray();
self.EditingUser = ko.observable();
self.detailedNote = ko.observable();
self.EditUser = function(user) {
self.EditingUser(user);
$("#userModal").modal("show");
};
this.addNote = function(user) {
var note= new Note("original")
self.detailedNote(note);
$("#addJobNoteModal").find('.btn-warning').click(function() {
user.notes.push(note);
$(this).unbind('click');
});
$("#addJobNoteModal").modal("show");
}
for (var i = 1; i <= 10; i++) {
self.Users.push(new User('User ' + i));
}
}
ko.applyBindings(new ViewModel());​

Change this:
$("#addJobNoteModal").find('.btn-warning').click(function() {
To this:
$("#addJobNoteModal").find('.btn-primary').click(function() {
You were targetting the wrong button :)

I think the problem after all was that you must bind to "value:" not "text:" in a form input/textarea.

Related

PartialView is opening in another page

I am making a searchfield which triggers a request function returning partial view and according to result I want to show the response in partial view under the searchfield in the same page. User writes something to textfield and clicks the search button then under them result shows. I get the result but my partialview is opening in another page instead of under the searchfield in the same page. Also looks like my onClick function does not trigger.
My main View:
<div class="container">
<!-- Outer Row -->
<div class="row justify-content-center">
<div class="col-6 p-3">
<form class="form-group" method="post" action="/Books/BookDetail">
<div class="input-group">
<input type="text" name="barcodes" class="form-control bg-light border-0 small bg-gray-200" placeholder="Kitap Barkodunu giriniz..." aria-label="Search" aria-describedby="basic-addon2">
<button class="btn btn-primary" type="submit" id="myBtn" name="myBtn" onclick="showBook">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</form>
</div>
<br />
<div id="partialContent">
</div>
</div>
</div>
<script>
function showBook() {
$('#partialContent').load("/Controllers/BooksController/BookDetail");
}
</script>
Book Detail Controller:
public IActionResult BookDetail(string barcodes)
{
var request = $"?barcodes={barcodes}";
var products = _httpTool.HttpGetAsync<List<Products>>($"{AppSettings.ApiUrl}/GetProducts{request}");
if(products.Result.Count != 0)
{
ViewBag.result = "Success";
var product = products.Result[0];
return PartialView("_BookDetailPartial", product);
}
else
{
ViewBag.result = "Failed";
return View("AddBook");
}
}
_BookDetailPartial:
<div>
<h4>PartialCame</h4>
<br />
<h5>#Model.Author</h5>
</div>
What is the problem here?
Thanks in advance!
onclick="showBook"
should be
onclick="showBook()"
And this path appears to be wrong: "/Controllers/BooksController/BookDetail" it should most likely be "/Books/BookDetail?barcodes=barcode"
I'm not sure what you mean about the partial view loading in another page. Could you give some more detail please?

Download text file via ASP.NET MVC dynamically changed

I have to generate file depending on input (checkboxes) and download it:
[HttpGet]
public FileResult GenerateFormatSettingsFile(IEnumerable<string> values)
{
var content = FileSettingsGenerator.Generate(values);
MemoryStream memoryStream = new MemoryStream();
TextWriter tw = new StreamWriter(memoryStream);
tw.WriteLine(content);
tw.Flush();
tw.Close();
return File(memoryStream.GetBuffer(), "text/plain", "file.txt");
}
And on my view this:
<button id="GenetateFormatSettingsFile" class="btn btn-primary" data-dismiss="modal" style="margin-right: 1500px">Generate</button>
$(document).ready(function() {
$("#GenetateFormatSettingsFile").click(function() {
var f = {};
var checkboxes = [];
$('input:checked').each(function() {
checkboxes.push($(this).attr("value"));
});
f.url = '#Url.Action("GenerateFormatSettingsFile", "Home")';
f.type = "GET";
f.dataType = "text";
f.data = { values: checkboxes},
f.traditional = true;
f.success = function(response) {
};
f.error = function(jqxhr, status, exception) {
alert(exception);
};
$.ajax(f);
});
});
</script>
The problem is the download doesn't start. How could I fix it?
If I do it with Html.ActionLink, the download starts, but I can't pass the values of checkboxes which is done by my ajax function above
Thanks!
Edit - that's how my check-boxes looks like:
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="modal" id="formatterSettings" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Settings</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="defaultG">To default view</label>
<input class="form-control" type="checkbox" value="Default" id="defaultG">
</div>
<div class="form-group">
<label for="extendedG">To extended view</label>
<input class="form-control" type="checkbox" value="Extended" id="extendedG">
</div>
/div>
</form>
</div>
<div class="modal-footer">
<div class="col-md-6">
<button id="GenetateFormatSettingsFile" class="btn btn-primary" data-dismiss="modal" style="margin-right: 1500px">Generate</button>
#Html.ActionLink("Generate!", "GenerateFormatSettingsFile")
</div>
<div class="col-md-6">
<a class="btn btn-primary" data-dismiss="modal" >Generate From Code</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Put a submit button in your form and POST your form synchronously (without ajax).
when a form is posted, values of all input elements (TextBoxes, CheckBoxes, ...) are sent to the server (with the request) and you don't need to do anything.

How to import parameters from post method

How do I get the get method called aidx parameter by post method?
When I start with the current code, it says that it is not defined.
aidx is the primary key, and I want to assign that primary key to the Family column.
<div id="blogpost" class="inner-content">
<form id="formdata"action="#Url.Action("Detail", "Board")" method="post" enctype="multipart/form-data">
<section class="inner-section">
<div class="main_blog text-center roomy-100">
<div class="col-sm-8 col-sm-offset-2">
<div class="head_title text-center">
<h2>#Html.DisplayTextFor(m => m.Article.Title)</h2>
#Html.HiddenFor(m => m.Article.ArticleIDX)
<div class="separator_auto"></div>
<div class="row">
<div class="col-md-8" style="margin-left:6%;">
<p>
<label>분 류 : </label>
#Html.DisplayTextFor(m => m.Article.Category)
</p>
</div>
<div class="col-md-8" style="margin-left:5%;">
<p>
<label>작성자 : </label>
#Html.DisplayTextFor(m => m.Article.Members.Name)
</p>
</div>
<div class="col-md-8" style="margin-left:10.6%;">
<p>
<label>작성일 : </label>
#Html.DisplayTextFor(m => m.Article.ModifyDate)
</p>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p>
<label style="font-size:x-large;">문의내용</label>
<br />
<br />
#Html.DisplayTextFor(m => m.Article.Contents)
<br />
<br />
<br />
<br />
</p>
</div>
</div>
<div class="dividewhite2"></div>
<p>
#if (User.Identity.IsAuthenticated == true)
{
<button type="button" class="btn btn-sm btn-lgr-str" onclick="btnEdit()">수정하기</button>
<button type="button" class="btn btn-sm btn-lgr-str" onclick="btnReply()">답글달기</button>
}
<button type="button" class="btn btn-sm btn-lgr-str" onclick="javascript:history.go(-1);">목록이동</button>
<br />
<br />
<br />
<br />
</p>
<div>
#Html.Partial("_Comment", new ViewDataDictionary { { "id", Model.Article.ArticleIDX } })
#Html.Partial("_CommentView", new ViewDataDictionary { { "CommentIDX", ViewBag.CommentIDX }, { "idx", Model.Article.ArticleIDX } })
</div>
</div>
</div>
<div class="dividewhite8"></div>
</section>
</form>
<script >
function btnEdit() {
if (#User.Identity.Name.Equals(Model.Article.Members.ID).ToString().ToLower() == true)
{
location.replace("/Board/Edit?aidx=#Model.Article.ArticleIDX");
}
else
{
alert("권한이 없습니다.");
}
}
function btnReply() {
location.replace("ReplyCreate?aidx=#Model.Article.ArticleIDX");
}
[HttpGet]
public ActionResult ReplyCreate(int aidx)
{
Articles articleReply = new Articles();
return View(articleReply);
}
[HttpPost]
public ActionResult ReplyCreate(Articles replyArticles, int aidx)
{
try
{
replyArticles.Family = aidx;
replyArticles.ModifyDate = DateTime.Now;
replyArticles.ModifyMemberID = User.Identity.Name;
db.Articles.Add(replyArticles);
db.SaveChanges();
ViewBag.Result = "OK";
}
catch (Exception ex)
{
ViewBag.Result = "FAIL";
}
return View(replyArticles);
}
You have several problem in your HTML and JavaScript:
You're not submitting anything, you're redirecting the page in JavaScript.
You're hiding the button if the user is not authenticated, but everybody can see, copy, and run the URL from your JavaScript.
Even if you fix #1 and your ReplyCreate() action gets called, it's expecting 2 parameters, but you're only sending one (aidx). The other parameter (replyArticles) will be always null.
Your code is vulnerable to CSRF attack.
To fix #1, you can add the parameter to your form instead of JavaScript, and change your button's type to submit:
<form id="formdata"
action="#Url.Action("Detail", "Board", null, new { aidx = Model.Article.ArticleIDX })"
method="post" enctype="multipart/form-data">
<div class="dividewhite2"></div>
<p><button type="submit" class="btn btn-sm btn-lgr-str">답글달기</button></p>
</form>
Or you can use a hidden field.
To fix #2, move the check outside the form and delete your JavaScript:
#if (User.Identity.IsAuthenticated) {
<form id="formdata"
action="#Url.Action("Detail", "Board", null, new { aidx = Model.Article.ArticleIDX })"
method="post" enctype="multipart/form-data">
<div class="dividewhite2"></div>
<p><button type="submit" class="btn btn-sm btn-lgr-str">답글달기</button></p>
</form>
}
To fix #3, you'll have to add the replyArticles parameter to your form or as a hidden field.
To fix #4, you'll need to add the forgery check to your form and your action.

ASP.NET MVC is it possible to use ajax.beginform inside a partial view?

Layout -> View -> Partial View
In the View:
<div class="col-md-8">
#{Html.RenderPartial("_komentari", commentlist);}
<div class="gap gap-small"></div>
<div class="box bg-gray">
<h3>#Res.commentwrite_title</h3>
#using (Ajax.BeginForm("postcomment", new { propertyid = Model.PublicID }, new AjaxOptions { UpdateTargetId = "commentsarea", HttpMethod = "Post", InsertionMode = InsertionMode.Replace }, null))
{
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label>#Res.commentwrite_content</label>
<textarea id="comment" name="comment" class="form-control" rows="6"></textarea>
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" value='#Res.commentwrite_btn' />
</div>
</div>
</div>
}
</div>
</div>
In the Partial View:
<div id="commentsarea">
<ul class="booking-item-reviews list">
#if (Model != null)
{
foreach (Comment item in Model)
{
<li>
<div class="row">
<div class="col-md-2">
<div class="booking-item-review-person">
<a class="booking-item-review-person-avatar round" href="#">
<img src="/assets/img/70x70.png" alt="Image Alternative text" title="Bubbles" />
</a>
<p class="booking-item-review-person-name">
#if (item.UserId != null)
{
<a href='#Url.Action("details", "user", new { userid = item.User.PublicId })'>#item.User.Username</a>
}
else
{
Anonymous
}
</p>
</div>
</div>
<div class="col-md-10">
<div class="booking-item-review-content">
<p>
#item.Content
</p>
<p class="text-small mt20">#item.DateOnMarket</p>
<p class="booking-item-review-rate">
#using (Ajax.BeginForm("reportcomment", new { comment = item.PublicId }, new AjaxOptions { UpdateTargetId = "reportscount", HttpMethod = "Post", InsertionMode = InsertionMode.Replace }, null))
{
<a id="submit_link" href="#">Spam?</a>
<a class="fa fa-thumbs-o-down box-icon-inline round" href="#"></a>
}
<b id="reportscount" class="text-color">#item.CommentReports.Count</b>
</p>
</div>
</div>
</div>
</li>
}
}
</ul>
</div>
<script>
$(function () {
$('a#submit_link').click(function () {
$(this).closest("form").submit();
});
});
</script>
View
Both scripts for Ajax are always included in the Layout (I'm already using Ajax on other pages too). On the View page, when I add a new comment, it is added in the database and shows the updated list of comments via ajax. Everything works fine.
Partial View
But if I want to report the comment as spam, I have to click on the link inside the Partial View (#submit_link), and after reporting, inside the #reportscount part, I want to show the updated number of reports of that comment. The actionresults returns that number like Content(numberofreports.toString()). It works but I get the number in a blank page?
Thank you very much.
It's better if you don't. The main issue is that, for security reasons, <script> tags are ignored, when HTML is inserted into the DOM. Since the Ajax.* family of helpers work by inserting <script> tags in place, when you return the partial via AJAX, those will not be present. It's better if you only include the HTML contents of the form in the partial, and not the form itself.

trumbowyg editor with vuejs

I am using the trumbowyg editor control in my vuejs spa. From the documentation I know that I can use the following code to set the contents of the editor.
$('#editor').trumbowyg('html','<p>Your content here</p>');
$('#editor').trigger('tbwchange');
However, it is not working for me in my VueJs App. I have an object that has a description key defined. I can console.log the description , but when I try to assign it to the editor control as mentioned above, it fails . I can see no error in the console but the text just won't show up in the editor.
Here is what I am going at the moment.
<template>
<div class="modal fade" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">
<span v-if="anouncement">Edit Anouncement</span>
<span v-else>New Anouncement</span>
</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" placeholder="enter anouncement summary here" class="form-control" v-model="anouncementObj.summary">
</div>
<div class="form-group">
<input type="text" placeholder="enter location here" class="form-control" v-model="anouncementObj.location">
</div>
<textarea class="note-view__body" id="anonDescription" v-model="description" placeholder="enter event description"></textarea>
</div>
<div class="modal-footer">
<button type="button" v-on:click="clear()" class="btn btn-link" data-dismiss="modal">Close</button>
<button type="button" v-on:click="performSave()" class="btn btn-link">Save</button>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props : {
anouncement : Object
},
data() {
return {
anouncementObj :{}
}
},
mounted () {
this.makeTextBoxReady();
this.anouncementObj = Object.assign({},this.anouncementObj, this.anouncement || {});
$('#anonDescription').trumbowyg('html',this.anouncement.description);
$('#anonDescription').trigger('tbwchange');
console.log(this.anouncement.description);
},
methods : {
makeTextBoxReady: function() {
$(document).ready(function() {
if (!$('html').is('.ie9')) {
if ($('.note-view__body')[0]) {
$('.note-view__body').trumbowyg({
autogrow: true,
btns: [
'btnGrp-semantic', ['formatting'],
'btnGrp-justify',
'btnGrp-lists', ['removeformat']
]
});
}
}
});
},
performSave : function() {
let description = $('#anonDescription').trumbowyg('html');
let formData = new FormData();
for (name in this.anouncementObj) {
formData.append(name, this.anouncementObj[name]);
}
if( !this.anouncementObj.id) {
this.anouncementObj.id = 0;
}
formData.append('description',description);
this.$http.post('/admin/anouncement/createOrUpdate', formData).then(response => {
// console.log(response);
if(response.data.status==200) {
alert(response.data.message);
this.$emit('getAnouncements');
}
})
},
clear: function() {
this.anouncementObj= {};
}
}
}
</script>
Can you please let me know what I am doing wrong here? I have also tried the nexttick approach but even that is not working.
I got it working. I was not using the correct bootstrap modal id. Please see this related question for more information.
This is the correct code.
if(this.anouncementObj && this.anouncementObj.description && this.anouncementObj.id) {
$('#'+this.anouncementObj.id+' #anonDescription').trumbowyg('html',this.anouncementObj.description);
$('#'+this.anouncementObj.id+' #anonDescription').trigger('tbwchange');
}

Resources