logo
down
shadow

Parse checkbox change value to Model and then to JSON object on button click in VIEW ASP.Net MVC


Parse checkbox change value to Model and then to JSON object on button click in VIEW ASP.Net MVC

Content Index :

Parse checkbox change value to Model and then to JSON object on button click in VIEW ASP.Net MVC
Tag : jquery , By : Tim Benninghoff
Date : November 28 2020, 11:01 PM

should help you out There are multiple issues with your code.
Starting with the controller method, you have a return statement inside the outer for loop which means that you only ever save the values of the 1st UserViewModel and then exit the method. To save all records, it needs to be
[HttpPost]
public ActionResult Create(List<UserViewModel> model)
{
    for (int i = 0; i < model.Count; i++)
    {
        for (int j = 0; j < model[i].Roles.Count; j++)
        {
            db.User.Add(new User { username = model[i].UserName, role = model[i].Roles[j].RoleName });                  
        }
    }
    db.SaveChanges();
    return RedirectToAction("Index", "User");
}
<a id="SubmitUserRoles" class="btn btn-success submit" value="Save">Save changes</a>
<input type="submit" class="btn btn-success submit" value="Save" />
var parsedData = @Html.Raw( new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));
data: $('form').serialize(),
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($('form').serialize()),
dataType: 'json',
@using (@Html.BeginForm(new { id = "UserForm" }))
@using (@Html.BeginForm())

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Checkbox enable/disable and check/uncheck and also button text change with a single button click


Tag : javascript , By : wpoch
Date : March 29 2020, 07:55 AM
seems to work fine Binding had to be used by force, I tried to use knockout but that's not actually helping.
So first of all, when I get the button value, without clicking it, by using document.getElementById and keeping it inside a variable stat, I had to make sure that if stat = 1, then another variable stat2 which has the value from the checkbox becomes 1 as well. Next, when stat2 = 1, checkbox will be checked. Similar thing was done in the else statement when stat = 0. So now stat2 = 0, and checkbox is unchecked.
if (stat == 1)
{

    document.getElementById("butt").value = "Activate";
    document.getElementById("chckbox").disabled = false;
    stat2 = 1;
    if (stat2 == 1) {

        document.getElementById("chckbox").checked = true;
    }
    else {

        document.getElementById("chckbox").disabled = false;
    }

}
else
{
    document.getElementById("butt").value = "Deactivate";
    document.getElementById("chckbox").disabled = true;
    stat2 = 0;

    if (stat2 == 0) {

        document.getElementById("chckbox").checked = false;
    }
        else {

            document.getElementById("chckbox").disabled = true;
        }

 }
function change() {

    var butt = document.getElementById("butt").value;

    if (butt == 'Deactivate')
    {
        document.getElementById("butt").value = "Activate";
        document.getElementById("chckbox").disabled = false;
        document.getElementById("stat").value = 1;
        document.getElementById("stat2").value = 1;

        if ((document.getElementById("stat2").value) == 1)
        {
            document.getElementById("chckbox").checked = true;
        }

        else
        {
            document.getElementById("chckbox").checked = false;
        }



    }

    else
    {
        document.getElementById("butt").value = "Deactivate";
        document.getElementById("chckbox").disabled = true;
        document.getElementById("chckbox").checked = false;
        document.getElementById("stat").value = 0;
        document.getElementById("stat2").value = 0;

        if ((document.getElementById("stat2").value) == 0)
        {
            document.getElementById("chckbox").checked = false;
        }

        else
        {
            document.getElementById("chckbox").checked = true;
        }


    }

}
self.InputConfiguration().IsActive = document.getElementById("stat").value;
self.InputConfiguration().IsMandatory = document.getElementById("stat2").value;


var activevalue = self.InputConfiguration().IsActive;
var check = self.InputConfiguration().IsMandatory;


if (activevalue == 1)
{
    document.getElementById("chckbox").disabled = false;
    //document.getElementById("chckbox").checked = true;


    check = 1;
    if (check == 1) {
        self.InputConfiguration().IsMandatory = 1;
    }

    else
    {
        self.InputConfiguration().IsMandatory = 0;
    }
}

else
{
    document.getElementById("chckbox").disabled = true;
    check = 0;
    //document.getElementById("chckbox").checked = false;

    if (check == 0) {
        self.InputConfiguration().IsMandatory = 0;
    }

    else
    {
        self.InputConfiguration().IsMandatory = 1;
    }

}

how to change view /model on button click?


Tag : javascript , By : user186831
Date : March 29 2020, 07:55 AM
it helps some times The best way, in my opinion, would be to bind the checked items to a mediating variable (checkedItems in this example), that doesn't immediately affect the view
<input type="checkbox" ng-model="checkedItems[$index]" ng-click="checkboxClicked($index)">
  $scope.checkcoxClicked = function(n){
    $scope.checkedItems[n] = !$scope.checkedItems[n];
  };
$scope.closePopover = function() {
   for (var i = 0; i < $scope.data.length; i++){
        $scope.data[i].checked = $scope.checkedItems[i];
   }
   $scope.popover.hide();
};

Change input -> change checkbox model without click


Tag : javascript , By : user140973
Date : March 29 2020, 07:55 AM
it fixes the issue My solution is plunkr
Listener on input change:
function trackInput(){
  if(sg.Value !== '' && sg.Value !== undefined) {
    sg.AnswerId = sg.answer.Id;
  } else {
    sg.AnswerId = false;
  }
};

How do I change a partial view with a radio button click in .Net MVC and have some of the model state passed along to th


Tag : asp.net-mvc , By : Bharath
Date : March 29 2020, 07:55 AM
will be helpful for those in need I had a few issues going. Aside from what Stephen mentioned above, I had two data models that needed to be represented in the same button group. To address that, I had to use Html.RadioButton instead of RadionButtonFor. Also, I needed to access the controller's established conversation with the client to access the model state of the current view. Once I got those in place, the partial view changes as desired. Below are the changes I made to fix my triggering problem.
Model
public class RetrieveAllModel
{
    public Guid ConversationId { get; set; }
    public List<RetrieveProductsModel> Products { get; set; }
    public RetrieveOffersModel Offers { get; set; }
    public string ProductType { get; set; }

}

public class RetrieveCatalogModel
{
    public List<BrowseDataItemModel> AvailableBrowseItems { get; set; }
}

public class RetrieveOffersModel : RetrieveCatalogModel
{
    public List<int> SelectedServiceIds { get; set; }
}

public class RetrieveProductsModel : RetrieveCatalogModel
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Count { get; set; }
}
@model OrderServiceClient.Models.RetrieveAllModel

@{
    ViewBag.Title = "Easy Order";
    int productCount = 1;
    string offers = "Offers";
}

@using (Html.BeginForm("ShowCatalog", "BrowseShopping"))
{
    //since offers are not part of the dynamic product list, they need to be specifically identified
    @offers<label>&nbsp;</label>
    @Html.RadioButton("catalogName", "Offers", true, new { catalogName = "Offers", conversationid = Model.ConversationId })
    <label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
    foreach (var type in Model.Products)
    {
        if (productCount > 0 && productCount % 5 == 0)
        {
            <br/>//break after every 5 products
        }
        @type.Name<label>&nbsp;</label>
        @Html.RadioButton("catalogName", type.Name, new { catalogName = type.Name, conversationid = Model.ConversationId })
        <label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
        productCount = productCount + 1;
    }
}

...

<div class="row">
        @{Html.RenderPartial("RetrieveCatalogs", Model.Offers.AvailableBrowseItems);}
</div>
@model List<OrderServiceClient.Models.BrowseDataItemModel>

@if (Model != null)
{
    <div class="col-lg-7 col-md-6 col-sm-12 offers-container" id="shoppingcatalog">
        <table class="table table-striped">
            <tr>
                <th>Data Type</th>
                <th>Name</th>
                <th>Price</th>
                <th></th>
            </tr>
            @foreach (var item in Model)
            {
                <tr class="offerList">
                    <td>@item.DataType</td>
                    <td>@item.Name</td>
                    <td>@string.Format($"{item.Amount,0:C2}")</td>
                    <td><a class="addService" dataType="@item.DataType" serviceId="@item.ServiceId" serviceName="@item.Name" amount="@item.Amount">Add</a></td>
                </tr>
            }
        </table>
    </div>
}
    public PartialViewResult ShowCatalog()
    {
        RetrieveCatalogModel rcm = new RetrieveCatalogModel();
        rcm.AvailableBrowseItems = new List<BrowseDataItemModel>();
        return PartialView("RetrieveCatalogs", rcm.AvailableBrowseItems);
    }

    [HttpPost]
    public PartialViewResult ShowCatalog(string catalogName, Guid conversationid)
    {
        if (catalogName.Equals("Offers"))
        {
            RetrieveOffersModel offers = new RetrieveOffersModel();
            var response = BrowseShoppingHelper.RetrieveOffers(conversationid, _client);
            offers.AvailableBrowseItems = BuildOffersBrowseDataItemsModel(response).ToList();

            return PartialView("RetrieveCatalogs", offers.AvailableBrowseItems);
        }
        else
        {
            var prodctFolderResponse = BrowseShoppingHelper.RetrieveProductFolders(conversationid, _client);
            var output = (RetrieveProductFoldersCommandOutput) prodctFolderResponse.Body.Output;
            RetrieveProductsModel rpm = new RetrieveProductsModel{Name = catalogName, AvailableBrowseItems = new List<BrowseDataItemModel>()};
            foreach (var folder in output.Folders)
            {
                if (!catalogName.Equals(folder.Name)) continue;
                var items = BuildProductBrowseItemsModel(
                    (RetrieveProductsInGroupCommandOutput) BrowseShoppingHelper
                        .RetrieveProductItems(conversationid, _client, folder).Body.Output);
                rpm.AvailableBrowseItems.AddRange(items);
                break;
            }
            return PartialView("RetrieveCatalogs", rpm.AvailableBrowseItems);
        }
    }
$(function() {
$("[name=catalogName]").on('change',
    function () {
        var $radio = $(this);
        var myurl = "ShowCatalog?catalogName=" + $radio.val() + "&conversationid=" + $(this).attr('conversationid');
        console.log("Catalog item is: " + $radio.val() + " and id is: " + $(this).attr('conversationid'));
        $.ajax({
            url: myurl,
            type: 'POST',
            success: function (data) {
                $("#shoppingcatalog").html(data);
            }
        });
    });
});

How to check and uncheck checkbox based on a button click (with text change of button) in Mvc?


Tag : asp.net-mvc , By : TRobison
Date : March 29 2020, 07:55 AM
To fix this issue You can use FromSql or ExecuteSqlCommand to execute stored procedure.
FromSql can only be used to execute raw SQL queries or stored procedures to get the data. You can’t use it for INSERT/UPDATE/DELETE. If you want to execute INSERT, UPDATE, DELETE queries, use the ExecuteSqlCommand. It returns integer value which indicates the count of affected rows.
if(!string.IsNullOrWhiteSpace(checkemails))
{
    dataContext.Database
           .ExecuteSqlCommand("Sp_Email_on_off @checkemails", checkemails);
}
Related Posts Related QUESTIONS :
  • If all divs have same style, remove element
  • How to click a jQuery Dialog button in TestCafe
  • Cannot reinitialise DataTable with Angular Datatable
  • How to add Class active on Click in Navbar
  • how to call fail method into jquery.get/post success method?
  • Slider with tabs
  • Jquery Get parent element from data function
  • Ho to put a new line in <p> tag in my jquery?
  • How can I use a text value as a mathematical operator?
  • DataTable columns values showing Only DefaultContent
  • JQuery select dynamically added elements
  • How to change an image source on hover?
  • How to bind jquery event to dynamically added multiple DOM elements?
  • How to get td values and store in array using Jquery?
  • How to add handler to dinamically created tr in JQuery?
  • How to Covert Html to PDF in Jquery?
  • Jquery before() and after() used to create a <div> container not inserting closing tags in after()
  • I want to delete previously added class
  • Open html page in same window after clicking on navlink
  • Datatable is not working when I populate table using smarty
  • How to change image based on the offset top of the content div
  • Find the index of table column with specific id
  • How to return value of $(window).resize()
  • How to optimize adding numerous elements dynamically into web page
  • Content slide down on top of page?
  • How to write if statement for when a specified option is selected in select tag in JQuery
  • HTML tags remove from textarea using jQuery
  • ShareThis not display properly when initially hidden
  • jquery - Bind datepicker event
  • How can I cause an element to move on mouse scroll using transform matrix?
  • How to add Custom summaries for autogenerated colums?
  • How to update table row with data from an array using jQuery
  • Cannot get the element in jQuery
  • How to search for two values in array at the same time?
  • Creating a floating document property control that is available in all tabs of Spotfire dashboard
  • Add a "wrapper" div tag to wrap other html div tags?
  • Reload form if I get an error when validate email
  • jQuery animate height in percentage scrolls to the top
  • How to add class for per string after comma?
  • ("ID").Value not working in ASP.net user control
  • HTML Color-picker with colors box
  • Initialize Kendo Grid grouped
  • jQuery click event triggers for all picture objects
  • addClass with the full match of id in jquery
  • Function is not called on click
  • jQuery ajax.error() for all errors except 403
  • Disable other option in same div, when first one is selected
  • How to clear input text
  • Rails Nested Forms Attributes not saving if Fields Added with jQuery
  • Jquery FancyBox target specific DIV ID?
  • jQuery table paging
  • Using Jquery UI Tab control in ASP.NET MVC
  • jQuery Datatable dynamic edit button attached to each row
  • JQUERY: Setting Active state on animated menu tabs
  • Filtering data with jquery
  • JQuery punctuation for spanish (ó, í, etc.) not working in IE8
  • Intro Bar like Stack Overflow
  • Jquery .filter() Question
  • ckeditor blur and dialog
  • How do I make a textbox take only numeric characters using jQuery?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com