gpt4 book ai didi

javascript - 从 Html Helper 中 knockout 的显示值

转载 作者:行者123 更新时间:2023-11-30 15:03:40 26 4
gpt4 key购买 nike

假设我正在使用一个

 @Html.TetboxFor(m => m.FirstName, new {  data_bind= "value:first_name" })

我正在从我的 MVC View 模型中填充它,我想将该值传递给我的 knockoutJs View 模型。我已经看到了从我的 View 模型中创建一个 javascript 对象的建议。我已经能够通过告诉 viewmodel

self.first_name = ko.observable($("#FirstName").val())

我尝试使用“文本”绑定(bind),它从 mvc View 模型中呈现我的数据,但不在 knockout View 模型中返回数据,“value”绑定(bind)清除我的 Html 助手,但确实将数据返回到 knockout View 模型。我还尝试使用“textinput”绑定(bind)。有没有比我正在使用的更好的方法,或者是直接从服务器填充 knockout View 模型的主要方法?谢谢

最佳答案

我知道我会因为给你一个替代答案而被打分,但这没关系,因为分享一种不同的解决问题的方法是值得的,它更简单、更强大。

如果您不介意某个建议,请远离 ASP.NET MVC Razor 模板,它并不强大,它会将您的后端与前端紧密耦合,与 ASP.NET Web 窗体没有太大不同。

此处作为 KnockoutJs 与 ASP.NET MVC 的强大示例,但没有用于将模型数据绑定(bind)到 View 元素的 Razor,而是完全使用 knockoutjs。一个关键的收获是 C# 模型是使用 knockout.mapping.js 在 KnockoutJs 中动态构建的。因此,当您向 C# 模型添加新属性时,它会自动在您的 Knockout ViewModel 中可用。

这是一个 .cshtml View 的片段,不使用 Razor 语法来绑定(bind)表单/输入模型:

@using System.Activities.Statements
@using System.Web.Optimization
@model Mvc.Models.ProjectModel

@{
ViewBag.Title = "Start New Project";
Layout = "~/Views/Shared/_BuildLayout.cshtml";
}


@section sideMenuCustomContent{
@Html.Partial("_PartialSidebarPricing")
}

@using (Html.BeginForm("StartSubmit", "Start", null, FormMethod.Post, new { @role = "form", id = "formStart", enctype = "multipart/form-data" }))
{
<input type="hidden" value="@Url.RouteUrl("UploadStep")" data-bind="valueWithInit: 'UrlWithIdUploadStep'" />
<input type="hidden" value="@Url.Action("GetProjectModel", "Start")" data-bind="valueWithInit: 'UrlRootGetProjectModel'" />
<input type="hidden" value="@Url.Action("StyleInfo", "Start")" data-bind="valueWithInit: 'UrlRootStyleInfo'" />
<input type="hidden" value="@Url.Action("GetCoverColorSwatchUrl", "Asset")" data-bind="valueWithInit: 'UrlRootGetCoverColorImage'" />


<div class="row">
<div class="col-lg-6 col-md-6 featuredTextContainer">
<div class="style-hero" >
<h1 class="style-title" data-bind="text: Style.StyleName"></h1>
<div class="style-start-price" >Starting at: <span data-bind="text: Application.FormatCurrency(BookBasePrice())"></span></div>
<div class="style-caption" >
<p data-bind="text: Style.DisplayText" ></p>
</div>
</div>
</div>

<div id="book-options-right-column" class="col-lg-4 col-md-6 build-right-column well-black">
<div class="form-group">
<input id="tbxPrjName" type="text" placeholder="Project Name" data-bind="value: Name" class="couture-input-underline couture-text-white placeholder-center text-center" />
</div>
<div class="form-group">
<input style="width: 80%;" type="text" class="couture-input-underline couture-text-white placeholder-center text-center" placeholder="Estimated Page Count" data-bind="value: PageCountEstimated, valueUpdate: 'afterkeydown'" />
<a data-toggle="popover"
class="popover-250w"
data-placement="bottom"
data-content="Estimate just to help you with pricing, exact page count will be tracked for you. Click the Hamburger Menu in left corner to see current pricing."
data-title="Estimated Page Count">
<i class="glyphicon glyphicon-question-sign"></i>
</a>
</div>


<input type="button" id="stampYes" data-bind="click: OnTextStampingYes, css: { 'selected': TextStamping }" class="btn-couture btn-couture-transparent btn-round" value="Y" />
<input type="button" id="stampNo" data-bind="click: OnTextStampingNo, css: { 'selected': !TextStamping() }" class="btn-couture btn-couture-transparent btn-round" value="N">
</div>
<div class="form-group" data-bind="visible: Style.HasBackCoverOption">
<label>Back Cover Image</label>
<a data-toggle="popover"
class="popover-250w"
data-placement="bottom"
data-content="You’ll be able to upload your back cover image on the next page."
data-title="Back Cover Image">
<i class="glyphicon glyphicon-question-sign"></i>
</a>
<br />
<span>
<input type="button" id="BackCoverYes" data-bind="click: onBackCoverChange, css: { 'selected': CoverImageBack }" class="btn-couture btn-couture-transparent btn-round" value="Y" />
<input type="button" id="BackCoverNo" data-bind="click: onBackCoverChangeNo, css: { 'selected': !CoverImageBack() }" class="btn-couture btn-couture-transparent btn-round" value="N" />
</span>
</div>
</div>
</div>
<div class="form-group">
<div data-bind="visible: !PricingPartialShowFinalTotals()">
<button type="button" class="btn-couture btn-couture-transparent btn-couture-white btn-couture-large" data-bind="text: PricingPartialSubmitBtnText, disable: PricingPartialSubmitLock, click: formSubmit"></button>
</div>
</div>
</div>
</div>



<div class="form-group">
<div data-bind="visible: !PricingPartialShowFinalTotals()">
<button type="button" class="btn-couture btn-couture-transparent btn-couture-white btn-couture-large" data-bind="text: PricingPartialSubmitBtnText, disable: PricingPartialSubmitLock, click: formSubmit"></button>
</div>
</div>

}@*using (Html.BeginForm())*@



@section scripts {
@Scripts.Render("~/bundles/knockout")
@*<script src="/Scripts/knockout.mapping.updateData.js"></script>*@
@Scripts.Render("~/bundles/knockout/build/start")


<script id="document-ready">
var viewModel = {};

$(function() {
pageInit();

}); //document.ready

</script>

<script id="ko-bind-page-init">
function pageInit() {

viewModel = ko.mapping.fromJS(@Html.Raw(Json.Encode(Model)), BuildStartViewModelMapping);
ko.applyBindings(viewModel);
viewModel.errors.showAllMessages(false); //ko.validation init
}
</script>

这是 knockout.mapping.js (~/bundles/knockout/build/start) 的一部分:

var viewModel = {};

var BuildStartViewModel = function (data) {
ko.mapping.fromJS(data, BuildStartViewModelMapping, this);
};

var BuildStartViewModelMapping = {
//'ignore': ['CoverColorName', 'PaperName', 'CoverColorId'],
create: function (options) {
var self = new BuildStartViewModel(options.data);
ko.BaseViewModel.call(self);
ko.BuildCommonViewModel.call(self);
self.IsStartView(true);

/*=================================================*/
//Custom observables not in data
/*=================================================*/
self.AdditionalTextStampingYes = ko.observable(false);
self.OriginalProjectName = ko.observable(self.Name());
/*=================================================*/

self.BuildStartBgClassGet = ko.computed(function () {
var styleName = self.Style.StyleName().toLowerCase();



return 'build-start-bg-' + styleName;
});

self.PageCountEstimated.subscribe(updatePageCount);

function updatePageCount() {
if (validatePageCountEstimated(self.PageCountEstimated())) {
self.PageCount(self.PageCountEstimated());
}
}


/*=================================================*/
//New Style Selected
/*=================================================*/
self.Style.StyleId.subscribe(onStyleIdNew);

function onStyleIdNew() {
if (!self.Style.StyleId())
return;

Application.LoadingDisplayToggle();

var url = $.concatUrl(viewModel.UrlRootGetProjectModel(), viewModel.Style.StyleId());

$.ajax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
async: true,
success: function (data) {
if (!data)
return;


ko.mapping.fromJS(data, BuildStartViewModelMapping, viewModel);
viewModel.errors.showAllMessages(false); //ko.validation init

//Refresh/Update Style Image
var $styleImage = $('#imgDisplayImage');
$styleImage.attr('src', '');
$styleImage.attr('src', data.Style.DisplayImage);
$('#hdnimage').val(data.Style.DisplayImage);

var $body = $('body');

console.log('TODO: UnComment When we have style images');
//$body.removeClass();
//$body.addClass('cover ' + self.BuildStartBgClassGet());

Application.LoadingDisplayToggle();
},
error: function () {
Application.LoadingDisplayToggle();
}
});
}

/*=================================================*/



self.formSubmit = saveData;

return self;

/*=================================================*/
//saveData/submit
/*=================================================*/
function saveData(data, event) {
//self.Name.isValidating.subscribe(function (isValidating) {
// if (!isValidating && self.errors().length > 0) {
// self.errors.showAllMessages(true);
// return;
// }
//});

//if (self.isValidating()) {
// setTimeout(function () {
// saveData(data, event);
// }, 50);
// return false;
//}

// ko.validation check if valid
if (self.errors().length > 0) {
self.errors.showAllMessages(true);
return;
}

var $form = $(event.currentTarget).closest('form');

if ($form.valid() && self.errors().length === 0) {
var copy = ko.toJS(this);
delete copy.errors;
delete copy.__ko_mapping__;

$.ajax({
url: $form.attr('action'),
type: 'POST',
dataType: 'json',
data: ko.toJSON(copy),
contentType: 'application/json; charset=utf-8',
success: function (response) {

var url = self.UrlWithIdUploadStep();
url = url.substr(0, url.lastIndexOf("/")); //remove id (could be StyleId and not ProjectId if new project)
url = $.concatUrl(url, response); //add project id to url, could be existing or new ProjectId

window.location.href = url;
},
beforeSend: function () {
self.PricingPartialSubmitLock(true);
Application.LoadingDisplayToggle();
},
error: function (result, error, errorThrown) {
self.PricingPartialSubmitLock(false);
Application.LoadingDisplayToggle();
Application.ToastrError(result.responseText);
}
});
}

return false;
};

}

};

这里是 Scripts/knockout.mapping.updateData.js,我认为您不需要它来开始使用此模式,但我包括以防万一:

/*
* Extension to the knockoutjs mapping plugin
* http://github.com/janhartigan/knockout-mapping-updatedata
* Requires KnockoutJS and the mapping plugin
*
* Dual licensed under the MIT or GPL Version 2 licenses.
* Jan Hartigan
*/
(function () {
/**
* A function that lets you "update from js" without overriding all the view model properties and methods. You just need to supply
* the viewModel, the original JS model on which you based your data (typically what you'd use in the mapping fromJS method), and the new JS
* object that has the updated information.
*
* @param Object viewModel
* @param Object dataModel
* @param Object jsObject
*
* @return Object (returns the viewModel)
*/
ko.mapping.updateData = function(viewModel, dataModel, jsObject) {
if (arguments.length < 3) throw new Error("When calling ko.updateData, pass: the view model, the data model, and the updated data.");
if (!viewModel) throw new Error("The view model is undefined.");

for (var i in dataModel) {
if (i in jsObject && i in viewModel && typeof dataModel[i] != 'function') {
viewModel[i](jsObject[i]);
}
}

return viewModel;
}

ko.exportSymbol('mapping.updateData', ko.mapping.updateData);
})();

关于javascript - 从 Html Helper 中 knockout 的显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46123787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com