Reputation: 889
Using javascript / jquery. I want to do this for every field that starts with
query.
queryForm['Foo'].value = queryForm['query.Foo'].value;
queryForm['Bar'].value = queryForm['query.Bar'].value;
queryForm['Baz'].value = queryForm['query.Baz'].value;
queryForm.submit();
And only if the queryForm['Foo'] exists.
Context: (You don't need to know this to answer my question, but it nice to know the context)
Above question is because of a fix / hack. Because I put the original Model in the ViewModel. Now Query is in the QueryViewModel.
@model QA.ViewModels.QueryViewModel
@using QA.ViewModels
@using QA.Enums
@{
var query = Model.Query;
}
<div class="form-group">
@Html.Required(model => query.Foo, "Describe the facts and circumstances that are relevant to the query", true, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-9">
@Html.EditorFor(model => query.Foo, new { htmlAttributes = new { @class = "form-control qa-tinymce-content" } })
@Html.ValidationMessageFor(model => query.Foo, "", new { @class = "text-danger" })
@Html.Hidden("Foo")
</div>
</div>
Upvotes: 1
Views: 73
Reputation: 36
Reading closely at what you did here: you put the old ViewModel in a new ViewModel and you do not want to rename the fieldnames in the partials.
Then why don't you add the needed fieldnames to the new ViewModel?
public Query Query { get; set; }
#region Variabeles in Query you do not wish to rename in the partial views.
public string Foo {
get { return Query.Foo; }
set { Query.Foo = value; }
}
#endregion
Upvotes: 2
Reputation: 3520
Your hack could be easily done with simple javascript like the following (not tested) :
for (let propertyName in queryForm){
if(!queryForm.hasOwnProperty(propertyName) || propertyName.indexOf("query.") !== 0){
continue;
}
let shortPropertyName = propertyName.substring(6);
if(!queryForm.hasOwnProperty(shortPropertyName)){
continue;
}
queryForm[shortPropertyName].value = queryForm[propertyName].value;
//if you want to delete the 'long' property:
// delete queryForm[propertyName];
}
//// (use let or var at your preference)
But, you should really ask yourself why you would want to do such things !
IMHO, you would better go with a proper and tidy model for your view.
Upvotes: 1