Call both c# and javascript in one button asp.net mvc

I have a button in ASP.NET MVC View. I found out that we can actually use c# commands in the view by adding @{ } before it. So I was wondering, how can my button call both the javascript function and adding data to the list passed with my Model in that view. Here is my model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Net.Mail;
using System.Web.Mvc;

namespace Dutch_Lady_Mailling_App.Models
{
    public class SendMailModel
    {
        [DataType(DataType.EmailAddress), Display(Name = "To")]
        [Required(AllowEmptyStrings = false)]
        public string ToEmail { get; set; }
        [Display(Name = "Body")]
        [DataType(DataType.MultilineText)]

        public string EMailBody { get; set; }
        [Display(Name = "Subject")]
        public string EmailSubject { get; set; }

        [Display(Name = "CC")]
        public string EmailCC { get; set; }
        [Display(Name = "BCC")]
        public string EmailBCC { get; set; }

        public string time { get; set; }
        public string resourceFile{get;set;}
        public string Data { get; set; }
        public bool sendtemplate { get; set; }
        public bool senddis { get; set; }
        public List<Contact> contacts { get; set; }
        public List<Distributor> distributors { get; set; }
        public string SelectedDis { get; set; }

        public string SelectedTemplate { get; set; }
        public IEnumerable<SelectListItem> Templates { get; set; }

    }

}

In my view, the button click will add the selected contacts into the List, also move the selected element to another div by calling jquery function without reloading the page, that's what I wanted

1 answer

  • answered 2018-07-11 03:39 Amin

    As I understood, you want to do two actions, one server-side and the other client-side. Of course if you call a server-side method, you will have a post back and all your page will be resent to you, so you can do all your job in server-side method because the page will be created again - I mean no need to javascript functions. But the way you can prevent this and the best approach for your scenario is using ajax for updating your list. Simplest way is using jquery ajax methods like $.ajax or its simplified version $.post or $.get (depending on your scenario and the way you want to send info to server). For example:

    $('#your_button_id').click(function(){
        $.post( "manage_contacts_api_url", "selected_contacts_ids", function( data ) {
            // update your div here
        });
    });