Post checkbox values using MVC property - asp.net-mvc

Is there any way to pass the checkbox values to the controller on checking from a list of checkbox without using any submit button or any jquery Ajax? I just want to use only asp.net mvc property.

As user1576559 sad in comment:
I want to submit the form when I'll check or uncheck any of the
checkboxs without using any jquery or ajax
Here it is:
#using (Html.BeginForm("Update", "Home"))
{
<p>Checkboxes:</p>
#Html.CheckBox("chk1", new { onchange = "this.form.submit()" }); <br/>
#Html.CheckBox("chk2", new { onchange = "this.form.submit()" }); <br />
#Html.CheckBox("chk3", new { onchange = "this.form.submit()" }); <br />
}

As per my understanding, you need to use #Html.CheckboxFor(m=>m.PropertyName) when you send the page to server then you get the updated checkbox status.

Related

Form post to multiple action methods based on model value in asp.net mvc

In Asp.net MVC, Is it possible to have a form post to two different actions based on model value when clicked on the same button?
Ex. - I want to add a new customer or update an existing customer on click of the same button "Save". Can the form be posted to two different action methods based on the customer's id value.
if the customer id value = 0 , then post it to "Create" acction method , if the customer id value is already present (not equal to 0), then post the form to "Update" action method?
Is this possible in asp.net mvc?
No You cant call multiple action on submit with fairly way,
You need to add hiddenfield for id
<input type="hidden" name="id" value="#model.Id" />
When you submit the form the value will be retrieve from model
And check the hidden field value is 0 or not
If 0 than the entity needs to create else it is for update
public ActionResult Save(Customer customer){
if(customer.id > 0){
// Update Entity
}
else{
// Create Entity
}
}
Yes. It is possible. There are multiple ways to do it.
1) You can conditionally set the form action attribute value based on your view model property value.
<form method="post" action="#(Model.Id==0?Url.Action("Create","Home")
:Url.Action("Update","Home"))">
<input type="text" name="FirstName" />
<button type="submit">Save</button>
</form>
2) Another option is, you can add html5 formaction to your submit button and the value of that attribute could be the url to create or update action method based on your Id property value.
#using (Html.BeginForm("Create", "Home"))
{
<input type="text" name="FirstName" />
<button type="submit"
formaction="#(Model.Id==0?Url.Action("Create","Home")
:Url.Action("Update","Home"))">Save</button>
}
When you specify the formaction attribute on a submit button, it will overrides the parent form's action attribute value.
3) Another option is to hijack the form submit event in javascript, prevent the default behavior (stopping the form submit) and then update the form's action attribute value to /create or /update and trigger form submit using javascript. You can keep the Id property value in a hidden field inside the form and read the value of that and use that to determine what should be the url for the form's action attribute value.
Assuming you have a hidden element for the Id of type int property in your page
#model YourViewModel
#using (Html.BeginForm("Create", "Home",FormMethod.Post,new {id="yourFormId"}))
{
#Html.TextBoxFor(a=>a.FirstName)
<button type="submit">Save</button>
#Html.HiddenFor(a=>a.Id)
}
and the javascript to hijack the form submit and update the form's action attribute value would be like
$(function () {
$("#yourFormId").submit(function(e) {
e.preventDefault(); // stop the normal form submit
var id=parseInt($("#Id").val());
var url=$(this).attr("action");
if(id===0)
{
url='/Home/Update'; // Use the Url.Action to be safe to generate this
}
// read the data attribute and update the forms action and do a submit
$(this).closest("form").attr('action', url).submit();
});
});
4) Another option is always submitting the form to Update or Create action and inside that method, based on the the Id property value, execute the code for Update or Create as needed.
Yes. This for the View case:
#mode MyModel
#{
string action = Model.Id == 0 ? "Create" : "Edit"
}
#using (Html.BeginForm(action, "MyController"))
{
// if Edit need Id
if(action == "Edit")
{
#Html.HiddenFor(model=> model.Id)
}
#Html.TextBoxFor(model >= model.Name);
<input type="submit" value="Save">
}

Sending form with Select List

I am using this code to post value of selected item from the view to the controller
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.MyVar, (SelectList)ViewData["List"])
<button name="Button" value="Valider">Valider</button>
}
Is there a way to send the value when the selection change in the select list (without the need to click on the button) ?
If you name the SelectList in the ViewData the same as the name of the variable in your Model, MVC will figure the rest out for itself.
So your dropdown would look like:
#Html.DropDownList(ViewData.MyVar, String.Empty)
This is as opposed to naming your ViewData item 'List'.
yes you can do it via JQUERY, on dropdown selection change post the form via jquery:
add id to drop down:
#Html.DropDownListFor(model => model.MyVar, (SelectList)ViewData["List"], new { id="SomeId"})
and write jquery event:
$(function(){
$("#SomeId").change(function(){
$(this).closest("form").submit(); // this will post the form
});
});

How to load records in MVC-view on demand

I am developing MVC application and using razor syntax.
In this application I am giving comment facility.
I have added a partial view, which loads the comment/Records from DB.
currently, data get loaded as soon as that view get called, which I want to avoid it.
I wan to load the data only when user click on the Button, which is on that view.
This is a code of the button.
<input type="button" value="Show" id="ShowId" onclick="LoadData()"/>
And
below Code should be executed when user click on the button.
#foreach (var item in Model)
{
<div id="OwnerName">
<span class="EmpName"> #Html.ActionLink(item.Owner.FullName, "Details", "EMployee", new { id = item.OwnerId }, new { #style = "color:#1A6690;" })</span>
#Html.DisplayFor(ModelItem => item.CommentDateTime)
</div>
<p class="CommentP">
#Html.DisplayFor(ModelItem => item.CommentText)
</p>
<br />
}
How to do this ?
Here are concrete examples of loading data on demand:
JQuery AJAX with ASP.NET MVC
Load partial page in jquery and ASP.Net MVC
Follow their logic and adapt to your case.
Update
Ajax will do the work either (look into comments). Thanks webdeveloper
Hope this helps
You want to load comments from server after user click the button? The simplest way is use Jquery. Create action which will return PartialViewResult and then make ajax request with jquery.

MVC 2 jQuery validation & ajax form

I want to use jQuery ($.post) to submit my html form, but I want to use the client side validation feature of MVC 2. Currently I hook up the post function to the "OnSubmit" event of the form tag, but I can't hook into the validation, ideally I want to be able to do
if (formIsValid) {
$.post('<%=Url.Action("{some action}")%>'...
}
Please note, Client side validation is working with jQuery.validation, I just can't get it to test if the validation was successful or not before I post my data.
Andrew
The final solution
<%
Html.EnableClientValidation();
using (Html.BeginForm("Register", "Account", FormMethod.Post, new { id = "registrationForm" })) {
%>
...
<button type="submit" onclick="return submitRegistration();">Register</button>
<%
}
%>
<script type="text/javascript">
function submitRegistration() {
if ($("#registrationForm").valid()) {
$.post('<%=Url.Action("{some action}")'...
}
// this is required to prevent the form from submitting
return false;
}
</script>
You can initiate jQuery validation on the button click event. Place the following inside your button-click event-handler:
if ($('form').valid())
//take appropriate action for a valid form. e.g:
$('form').post('<%=Url.Action("{some action}")%>')
else
//take appropriate action for an invalid form
See the Validation plugin documentation for more information.

Click event is launching only once

I have a form in which I have many checkboxes. I need to post the data to the controller upon any checkbox checked or unchecked, i.e a click on a checbox must post to the controller, and there is no submit button. What will be the bet method in this case? I have though of Ajax.BeginForm and have the codes below. The problem im having is that the checkbox click event is being detected only once and after that the click event isnt being launched. Why is that so? How can I correct that?
<% using (Ajax.BeginForm("Edit", new AjaxOptions { UpdateTargetId = "tests"}))
{%>
<div id="tests">
<%Html.RenderPartial("Details", Model); %>
</div>
<input type="submit" value="Save" style="Visibility:hidden" id="btnSubmit"/>
<%}
%>
$(function() {
$('input:checkbox').click(function() {
$('#btnSubmit').click();
});
});
Try $('#myForm').submit().
Check this post out. I think you need to use the each keyword and bind so that binding is done everytime.
As a debugging step, try doing something else during the click event, like
$('input:checkbox').click(function() {
$('#debugDiv').append('click event fired at ' + new Date().toString());
});
to see if the issue has something to do with the form submission.
Something else you can try is using jQuery's live function instead of click: http://api.jquery.com/live/

Resources