MVC3: Geting values of cloned objects - asp.net-mvc-3

I have a drop down list with options from a model; and I want to add a similar drop down list when the user clicks on a button. My drop down list and button are defined as
<div id="parent">
<div class="id">
#Html.DropDownListFor(m =>m.mymodel)
</div>
</div>
<input type="button" value="submit" onclick="JSFunc()"/>
And the function, JSFunc() is
var control = document.getElementById('id').cloneNode( true );
document.getElementById( 'parent' ).appendChild( new );
How can I get the value of the clone objects from the controller?

You must set the name attribute of a newly-created <select> to something unique that matches a parameter name in your controller.
(or parameter property name, or anything else depending on the model binder and your situation)

Related

Laravel 5.1, update multiple values from checked checkbox

In Laravel 5.1, I need to update multiple values from checked checkbox.
I can edit some registries from a table by clicking the edit button for each registry, and that button send me to the edit view
(This is de edit view for a single registry)
With the url: http://myapp/someroute/2246/edit where 2246 is some id.
Inside that edit I can update 4 fields. One of those fields is called "my state" and can have the values 1, 2 or 3.
Now, I have to make a multi select edit feature, where I can check every row of the table that I need to update simultaneously (each have the name=someid) and then click some button called "Validate", and update for evey row only 1 field, the my state field, and the new value will be always 1 (in the picture the values are string but thats only for the view).
The question is: how can I call the method update for every id that I'm selecting in the view? every input checkbox has it's own name which is the id of the registry that I will update.
The update method just validate some values from the view and then call some myeditmethod, but in this case I will jump the update and go directly to myedit which is someting like:
public function myedit(Request $request, $id) {
$obj = Self::findOrFail($id);
$obj->fk_id_comuna = $req['fk_id_comuna'];
$obj->fk_id_user = $usuario_id;
$obj->date = \Carbon\Carbon::now();
$obj->fk_id_my_state = $estado; //THIS IS THE ONLY FIELD THAT I WILL EDIT, ALWAYS WITH THE SAME VALUE `1`
$obj->save();
I was trying the make a form for that Validate button but I don't know how to handle multiple id in one call on the edit method.
<form action="{!! route('myroute.update', ['id' => [HERE, HOW CAN I PASS MULTIPLE ID FROM THE CHECKED CHECKBOX] ]) !!}" method="POST">
<input type="submit" class="btn btn-primary pull-right" value="Validar" />
</form>
I was thinking on a javascript function which collect in a array every checked checkbox name and call the myedit method directly, without the formof the view, could be?
About passing multiple values as one Request value.
Assume you have form like this:
<form method="post">
<input type="checkbox" name="options[]" value="foo"/>foo<br/>
<input type="checkbox" name="options[]" value="bar"/>bar<br/>
<input type="checkbox" name="options[]" value="buz"/>buz<br/>
<input type="submit" value="Submit" />
</form>
Your request('options') would be an array: ["foo", "bar", "buz"].
Than you can iterate over options using foreach.
Inside your update method you can go with:
foreach ($option as request('options')) {
//put your previous code here, so it'd be applied for every option
}
In JS I did this:
var optionsChecked = [];
$('.options:checkbox:checked').each( function(){
optionsChecked .push($(this).val());
});
Then in ajax:
$.ajax({
type: 'POST',
data: {'id': optionsChecked },
etc
Then in PHP:
$all = $request->input('id');
foreach ($all as $id){
//whole obj->* = *;
$obj->save();
}

ASP.Net Core 2.0 MVC dynamic model updating

I'm trying to build a dynamic view, where I can pass a list of properties that need to be filled in by the user.
The collection of properties is dynamic, so I can't build the view that displays specific properties.
I've been able to display the property names and their initial values, and the user can change the values on the screen, but those updated values don't make it to the controller action that would update the model.
I've tried using a dynamic model, as well as a list of key/value pairs.
I'm thinking that it has something to do with the over-posting protection. Since the properties are dynamic, I can't list them in the Bind attribute in the update action.
Here's the controller action methods:
public IActionResult Test()
{
dynamic testObj = new ExpandoObject();
testObj.IntProperty = 100;
testObj.StringProperty = "A String Value";
return View(testObj);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Test(ExpandoObject model)
{
return Ok();
}
Here's the view:
#model dynamic
#{
ViewData["Title"] = "Test";
}
<form asp-action="Test" method="post">
<div class="form-horizontal">
#foreach (var propertyName in ((System.Collections.Generic.IDictionary<string, object>)Model).Keys)
{
<div class="form-group">
<label class="col-md-2 control-label">#propertyName</label>
<div class="col-md-10">
#Html.TextBox(propertyName, ((System.Collections.Generic.IDictionary<string, object>)Model)[propertyName])
</div>
</div>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
</form>
This is a new application, and I'm doing code-first - so the model can be changed somewhat. All I really need to do is to be able to have different properties that can be updated.
Thanks in advance.
I recommend that you do not rely on the IModelBinder for this purpose at all and why I recommend this is because the form data that is passed between the controller and view is dynamic in terms of structure. A better, yet more troublesome, solution would be to get the form data directly out of the HttpContext.Request.Form. This type has an indexer which allows you to access the posted values by their names. For example
var name = HttpContext.Request.Form["name"].FirstOrDefault();
The .FirstOrDefault() (or SingleOrDefault(), this throws an exception when finding more than a value that meets a condition in a collection) is called assuming that there would be a single value (or a single value that meets a condition) for the "Name" input. However, when you have an array of those, you can get the values either in a foreach loop, or using linq methods, or directly by an index. For example:
var name = HttpContext.Request.Form["name"].FirstOrDefault(x=> x.ToString().StartsWith("x"));
var name = HttpContext.Request.Form["name"][0];

How to get checked checkbox value from html page to spring mvc controller

im using spring mvc framework with thymeleaf template engine
the problem is , i have 1 page with multiple check box iterated sing thymeleaf th:each iterator.When i clicked multiple check boxes i want to pass check box values to the controller method..
html content
<table>
<tr th:each="q : ${questions}">
<h3 th:text="${q.questionPattern.questionPattern}"></h3>
<div>
<p >
<input type="checkbox" class="ads_Checkbox" th:text="${q.questionName}" th:value="${q.id}" name="id"/>
</p>
</div>
</tr>
</table>
*Controller*
#RequestMapping(value = Array("/saveAssessment"), params = Array({ "save" }))
def save(#RequestParam set: String, id:Long): String = {
var userAccount: UserAccount = secService.getLoggedUserAccount
println(userAccount)
var questionSetQuestion:QuestionSetQuestion=new QuestionSetQuestion
var questionSet: QuestionSet = new QuestionSet
questionSet.setUser(userAccount)
questionSet.setSetName(set)
questionSet.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
questionSetService.addQuestionSet(questionSet)
var list2: List[Question] = questionService.findAllQuestion
var limit=list2.size
var qustn:Question=null
var a = 1;
for( a <- 1 to limit ){
println( a );
qustn= questionService.findQuestionById(a)
questionSetQuestion.setQuestion(qustn)
questionSetQuestion.setQuestionSet(questionSet)
questionSetQuestion.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
questionSetQuestionService.addQuestionSetQuestion(questionSetQuestion) } "redirect:/teacher/Assessment.html" }
I think you pretty much have it. With a checkbox, you can only send one piece of information back with the form...that being the value. So if you are trying to determine which checkboxes are checked when the user clicks the submit button, then I would have the checkboxes all use one name...like "id" (exactly like you have). Value is the actual id of the question (again like you have). Once submitted, "id" will be a String array which includes all the values of the checkboxes that were checked.
So your controller method needs to take param called "ids" mapped to parameter "id" which is a string[]. Now for each id, you can call questionService.findQuestionById.
(I'm not a Groovy guru so no code example sry :)
I have used JSTL with JSP and thymeleaf was something new. I read the THYMELEAF documentation.
There is a section which explains multi valued check boxes.
<input type="checkbox"
class="ads_Checkbox"
th:text="${q.questionName}"
th:value="${q.id}" name="id"/>
In the above code we are not binding the value to the field of the command object. Instead try doing this
<input type="checkbox"
class="ads_Checkbox"
th:text="${q.questionName}"
th:field="*{selectedQuestions}"
th:value="${q.id}" />
here the selectedQuestions is an array object present in the spring command object.

Razor: hidden password control (2 page registration)

I'm creating a 2-page registration process in razor. The difficulty here is gathering data (username, passwd, etc) on the first page and using hidden input variables to store the first page's data on the second.
here is my hidden code:
<div id="hidden vals" style="display:none;">
#Html.HiddenFor(model => model.userRegisterModel.UserName)
#Html.HiddenFor(model => model.userRegisterModel.studentFirstName)
#Html.HiddenFor(model => model.userRegisterModel.studentlastName)
#Html.HiddenFor(model => model.userRegisterModel.Email)
#Html.PasswordFor(model => model.userRegisterModel.Password)
#Html.PasswordFor(model => model.userRegisterModel.ConfirmPassword)
</div>
the challenge is in password and confirmpassword. I don't want to use a hidden field of password type but i want my password persisted but not revealed in page-source. but the "PasswordFor" has a side problem that it "depopulates" the values and makes the user re-populate.
So to re-state, I need my password and confirm persisted and preferably not shown to the user. Moist importantly I need my password and confirm values not hidden from "view source"
My alternative strategy is to use a session variable to store all "page 1 values" but this has other pitfalls id prefer to avoid.
Can I suggest a different approach? Instead of two-page, use two-DIV.
You can still leverage things like validation (client & remote) and make sure the user can't advance without a valid form. If there are things that need to be loaded and/or created for the second page, you can do that with Ajax and your form could still live on the page, without the use of the hidden fields or the session variables/timeouts.
<form ...>
<div id="part-one">
<!-- content... -->
</div>
<div id="part-two" style="display:none;">
<!-- content... -->
</div>
<div>
<button type="button" id="prev-div">Previous</button>
<button type="button" id="next-div">Next</button>
<button disabled="disabled" id="next-div">Submit</button>
</div>
</form>
The buttons stay visible, you can toggle the state of them with jQuery, and if your requirements change an update to your model class and view are all that is required (if you're using model binding).
Yes. Keep them in Session and access it in the second page / action method.
And Make sure to clear that particular Session variable once you read from that for persistant storage.

DropDownList MVC3

I am doing a edit operation on a record in Grid . One of the column is DropDownValue.
When I go to Edit View , depending upon this dropdownvalue , I make few fields editable and readable. And , One more point is here, I didnt select the dropdown Yet, But whatever its value selected before is the one which I should retrieve. I know I have to use jQuery .But I didnt exact Syntax to do tht.
Here is my dropdown
<div id="dvstatus">
#Html.DropDownListFor(model => model.Study.StudyStatusId, Model.StatusSelectList, new { id = "ddlStatus" })
</div>
NOT SELECTED VALUE, BUT THE VALUE WITH WHICH IT IS LOADED
My requirement is how to get the dropdown value item , when it is loaded onto .cshtml
If you're not referring to the selected value of the dropdown then just pass the value from the controller to your view using your model if you're using a strongly-typed view or pass it some other way like using ViewBag and just set the value when it's passed on view.
You can add a hidden field to save the initially loaded value. Eg
<div id="dvstatus">
#Html.HiddenFor(model => model.Study.StudyStatusId)
#Html.DropDownListFor(model => model.Study.StudyStatusId, Model.StatusSelectList, new { id = "ddlStatus" })
</div>
Then you can use java script to compare current value of the drop down and the value of the hidden field(which has the initial value).

Resources