1

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>
1
  • 2
    Don't use a "hack"; just fix your code so that it works properly in the first place. Trying to do something like this with JavaScript to cover for a mistake in the code is just a bad idea all around. Commented Jun 30, 2017 at 14:49

2 Answers 2

2

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 
Sign up to request clarification or add additional context in comments.

1 Comment

I will test this and see if it works for me. Seems like the most easy way to solve my problem.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.