.NET MVC

385

Solutions

291

Contributors

Microsoft’s ASP.NET MVC is a web application framework that implements the model–view–controller (MVC) pattern. As an open-source software, it’s set apart from the ASP.NET Web Forms component, which is proprietary.

Share tech news, updates, or what's on your mind.

Sign up to Post

Hi Guys!!!

I'm new to MVC C# coding and I really need your help.

I have a left menu that I want to be populated from my database and I'm not sure how to do it.

Thank you in advance for taking the time to help me with this.

I have two tables a parent table and a child table 

Parent table called: RuleSet

RuleSetID       |     RuleSet                 |    CreatedDate   |     CreatedBy 
1                             Blended                      11/12/2019            Y000001
2                             OSCMain                     11/12/2019            Y000001
3                             Questionnaire            11/12/2019            Y000001

Child table called: RuleIdentifier

RuleIdentifierId    |    RuleSetId    |    RuleIdentifier            |      CreatedDate   |    CreatedBy
1                                     1                       Blended_00010                 11/12/2019            Y000001
2                                     2                       OSCMain_0049                  11/12/2019           Y000001
3                                     2                       OSCMain_0010                  11/12/2019           Y000001
4                                     2                       OSCMain_0122                  11/12/2019           Y000001
5                                     1                       Blended_0234                    11/12/2019           Y000001
6                                     3                       Questionnaire_02 

Open in new window

0
Ensure you’re charging the right price for your IT
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Hi Experts,

This is my view model.

public class ResellerHomePageViewModel {
        public IList<SelectListItem> SelectList { get; set; }
    }

Open in new window


I have a dropdown list called "SelectPartner"
<select id="SelectPartner">
<option id="defaultOption" value=""></option>

</select>

Open in new window


How can I bind the value of "SelectList " (Model. SelectList ) to the dropdown list "SelectPartner" using jQuery on document.ready function?

Thanks in advance.
0
How can I make my text area editor disabled if the user typed in more than 4000 characters?

I have tried the disable syntax but it's not working


<link type="text/css" rel="stylesheet" href="~/Content/CWScss/jodit.min.css">
<script type="text/javascript" src="~/Scripts/jodit.min.js"></script>


 jQuery(function () {
            var maxLength4000 = 4000;
            $(document).on("keyup paste blur click touchend", function () {
                var textlen = maxLength4000 - $("#AttributesAndValue").val().length;

                 //Here I want to say if textlen more than 4000 char then disable my text editor 
                //my disable is not working 

                if ($("#AttributesAndValue").text().length == 4000 || textlen <= -1) {
                    $('#AttributesAndValue').prop("disabled", true);
                }


                $('#rchars').text(textlen);
            });
            $('#AttributesAndValue').each(function () {
                var AttributesAndValue = new Jodit(this);
                AttributesAndValue.setDisabled();
            });
        });


                  <div class="form-group purple-border">
                        Attribute(s) and Value(s)
                        @Html.TextArea("AttributesAndValue", new { @class = "form-control", @style = "width:77%" })
                          <div id="ValidateAttributesAndValue" style="color:#bc0606;font-weight:bold;">Required Field</div>
                        <span 

Open in new window

0
Count HTML text area characters not to exceed 4000.  

I'm not able to display the total count of characters.

<link type="text/css" rel="stylesheet" href="~/Content/CWScss/jodit.min.css">
<script type="text/javascript" src="~/Scripts/jodit.min.js"></script>

 $('#AttributesAndValue').each(function () {
            var AttributesAndValue = new Jodit(this);
            //editor.value = '<p>start</p>';
        });

        var maxLength4000 = 4000;
        $('#AttributesAndValue').keyup(function () {
            // var textlen = maxLength4000 - $(this).val().length;
            $('#rchars').text(textlen);
        });


                   <div class="form-group purple-border">
                        Attribute(s) and Value(s)
                        @Html.TextArea("AttributesAndValue", new { @class = "form-control", @style = "width:77%" })
                         <span id="rchars">4000</span> Character(s) Remaining
                        <div id="ValidateAttributesAndValue" style="color:#bc0606;font-weight:bold;">Required Field</div>
                    </div>

Open in new window


Thanks,
Lulu50
0
Does Entity Framework sometimes auto-convert DateTime to EST?

My Javascript call is making an MVC call to a C# web method with a date that is set to midnight. But, when I query the database, I see the correct date was added to the DB table, as expected. However,  there is time added, and it turns out to be UTC time:

I am on the East Cost of the US and am currently 4 hours behind UTC/GMT.

Here is the format of the data:

2019-11-01 04:00:00.000

I was expecting:
2019-11-01 00:00:00.000

Since, the JSON date/time I am passing in was at midnight.

Is there a setting in Entity Framework which may cause this?

Or, is there a JSON parser doing this?


Thanks
0
Hi,

I have to add a text editor to my project and I wonder if you anyone know where I can download an example.

The user should be able to bold and change the color of the text. so that's why I need to add a text editor to my project.  

Thanks,
lulu
0
Can you please tell me why this routine is not showing values in the text box when i click in the text area?
screenshot.JPG
      private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListBox i = sender as ListBox;
            if (i.SelectedIndex != -1)
            {
                listBox1.SelectedIndex = i.SelectedIndex;
                listBox2.SelectedIndex = i.SelectedIndex;
                txtID.Text = listBox1.SelectedItem.ToString();
                txtName.Text = listBox2.SelectedItem.ToString();               
            }
        
        }

Open in new window

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace InsertUpdateDel
{
    public partial class Form1 : Form
    {
        SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Lenovo\Documents\Visual Studio 2012\Projects\InsertUpdateDel\InsertUpdateDel\Database1.mdf;Integrated Security=True;User Instance=True");
        SqlCommand cmd = new SqlCommand();
        SqlDataReader sd;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
                cmd.Connection = cn;
                loadlist();
        }

        private void button1_Click(object sender, 

Open in new window

0
Can you please help me in that error?
screenshot.JPG
namespace InsertUpdateDel
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.txtID = new System.Windows.Forms.TextBox();
            this.txtName = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.listBox2 = new System.Windows.Forms.ListBox();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            

Open in new window

0
I have a Asp.Net Core Application.

On one of my views I have an anchor tag like this this.

<a asp-controller="Speaker"
   asp-action="Index">All Speakers</a>

i have a CSS class that looks like this:

.LinkStyle1 a:link { color: #0000FF; }

Is there a way to add this class style to the asp-controller link tag?

One way that works is like this:

<span class=“LinkStyle1”><a asp-controller="Speaker"
   asp-action="Index">All Speakers</a></span>

Is there a better way to apply a css class to this asp-controller tag?
0
I like to know is there any dll for edit image for website. purpose is to edit image & add text & mark circles on image before save.
0
Starting with Angular 5
LVL 19
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

I have buttons using URL.Action and cannot get them to open in a new tab.  I've tried target=_blank with no luck!

 <button class="btn btn-info" style ="width:90px;" onclick="location.href='@Url.Action("LocationDetails", "Location", new
                                                                                                                 { id = @Model.id                                                                                                 
                                                                                                                 }
                                                                                         
                                )'">
                                Details
                            </button>

Open in new window

0
I have the following json string. how  to read it in c# FOR  LOOP?

{Employee:[{"principalfirstname":"xxx","principallastname":"xxx","principalmiddlename":"xxx","principalnameonbond":"xxx","principaldba":"xxx","principalentity":"USA","principalyearinbusiness":"xxx","principaltaxid":"","principaladdress":"xx","principalcity":"xxx","principalstate":"TN","principalzip":"111","principalcounty":"","principalphoneno":"xxx","principalemail":"","principalfaxno":"","vin":"","licenseplatenumber":"","driverlicensenumber":"","door":"","bondstate":"","bondamount":"","premium":"","bondterm":"","creditcardfullname":"","creditcardnumber":"55555555533331111","creditcardchargeamount":"","creditcardexpdatemm":"","creditcardexpdateyyyy":"","creditcardcvc":"","creditcardaddress":"","creditcardcity":"","creditcardstate":"","creditcardzip":""}]}

Open in new window

0
Hello Experts,

I'm new to MVC and JQuery web development. I'm trying to bind the data to my datatable using JSon object. Below is the sample code:

View
<div id="mdlMsg" class="modal fade" tabindex="-1" role="dialog">
            <div class="table-responsive m-t-40">
                <table id="dtData" class="display nowrap table  dataTable" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <th>Col1</th>
                            <th>Col2</th>
                        </tr>
                    </thead>
                    <tbody id="tblbody"></tbody>
                </table>
            </div>
        </div>

Open in new window


Controller
public async Task<ActionResult> Test()
{
 string resp = "";
  var msg = new Dictionary<int, string>();
msg .Add(1, 'Row 1');               
msg .Add(2, 'Row 2');       
      resp= Newtonsoft.Json.JsonConvert.SerializeObject(msg, Newtonsoft.Json.Formatting.Indented);
return resp;
}

Open in new window


Javascript
$.ajax({
        type: 'post',
        url: url,
        processData: false,
        contentType: false,
        data: files,
        success: function (resp) {
 $('#mdlMsg').modal({ show: true })
                var jsonTst = $.parseJSON(resp);
                $('#dtData').dataTable({
                    "bAutoWidth": false,
                    "aaData": jsonTst.data,   //this is your JSON object, which is what is showing in your post above with console.log(data)
                    "aoColumns": [{
                        "jsonTst": "Col1"
                    }, {
                            "jsonTst": "Col2"
                    }]
                });
});

Open in new window


The modal popup shows with no data and also I want to fix my Modal popup to be middle of the page.

Thanks,
ASPDEV
0
I have the following ajax codes, and want to send Json data to MVC Controller.
Can you show me how to do that  on MVC Controller?
Thanks

function Submit(domain) {
    //alert("Thank You");
    var x = $('#formdiv *').serializeArray();      
    var data = {};
   $.each(x, function (i, field) {
        data[field.name] = field.value;
   });
    var json = JSON.stringify(data);   
    alert(json);
    $(document).ready(function () {
        $.ajax({
            url: domain + "/Api/ReceiveJson",
            type: "POST",
            data: {json},
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (data) {alert('Success');},
            error: function (msg) { alert(msg); }
        });
    });
    return false;
}

Open in new window

0
If I have just a simple web form in html and  a submit button., and I want to create json file basically,
when the button is clicked, capture, each id inside of the form in a loop. (My web form will be huge so I do not want to capture one by one).
then create json format, and  drop into root directory like www.hello.com\json\abc.json.

Is it possible?

In my web form I only use type=text and <select></select> and the id name will be header name  inside of json. Just keep it simple. and I do not use <form></form> just <a onclick=submitnow()>

Thanks,

<div class="col-md-6">
    <div class="form-group bd-t-0-force">
        <label class="form-control-label"><i class="fa fa-credit-card"></i> Card Number: <span class="tx-danger">*</span></label>
        <input class="form-control" type="text" name="ccnumber" value="Market St., San Francisco" placeholder="Enter Card No.">
    </div>
</div><!-- col-8 -->
<div class="col-md-2">
    <div class="form-group mg-md-l--1 bd-t-0-force">
        <label class="form-control-label"><i class="fa fa-credit-card"></i> Card Expiration Month: <span class="tx-danger">*</span></label>
        <input class="form-control" type="text" name="ccexpdatemm" value="" placeholder="Enter Card Expiration Date Month">
    </div>
</div><!-- col-4 -->
<div class="col-md-2">
    <div class="form-group mg-md-l--1 bd-t-0-force">
        <label class="form-control-label"><i class="fa fa-credit-card"></i> Card Expiration Year: <span 

Open in new window

0
Hello Experts,

I'm new to MVC devlopment, I was using Viewbag to pass the data from my controller to JS(jquery function). I want to know how can I read the List data and then assign to my grid. This is the sample code, I was getting error while reading the ViewBag.MyList in my JS function. How can I do this so I can get the list object. Later part once I get the list object, then I will bind the data with the grid.

Controller
public async Task<ActionResult> TestData(
string resp = "";
 var test = new List<Tuple<int, string>>();
test.Add(new Tuple<int, string>(1, 'R1'));
test.Add(new Tuple<int, string>(2, 'R2'));

if (test.Count > 0) {
ViewBag.MyList= Newtonsoft.Json.JsonConvert.SerializeObject(test);
}

resp = "test";
}

Open in new window


JavaScript
$.ajax({
        type: 'post',
        url: url,
        processData: false,
        contentType: false,
        data: files,
        success: function (response) {

 if (response == 'test')
{
var testList= JSON.parse('@Html.Raw(ViewBag.MyList)');
}
}

Open in new window

0
I have Javascript functions to set Hidden Form fields when a drop-down list changes and this works correctly.  Now I need to set those fields when the page loads as well.

My View:

<script src="~/Content/classes/Report.js"></script>

<script type="text/javascript">
    var Report = new ReportClass();
    Report.init();
    
</script>

    <div class="row">
        @using (Html.BeginForm("Report", "Location", FormMethod.Post))
        {
            <div class="col-xs-3">
                @Html.DropDownList("System", sl.getSystemList(), new
           {
               @type = "drop",
               @id = "System",
               @onchange= "setReportFilter()"
           })
            </div>

            <div class="col-xs-2 ">
                <button type="submit" class="btn btn-info">
                    Filter
                </button>
            </div>

        }

        <div class="col-xs-2 col-xs-offset-3">

            @using (Html.BeginForm("ExportReport", "Location", FormMethod.Post, new
            {
                @target = "_blank",

            }))

            {

                @Html.Hidden("ReportFilter")

                <button id="exportBtn" type="submit" class="btn btn-info" style="float:right">
                    Export To Excel
                </button>
            }

        </div>

    </div>

<script type="text/javascript">
    function setReportFilter() {

        var sys = document.getElementById("System");
        var sysSelection = 

Open in new window

0
Hi Experts,

I am trying to get the company name in document.ready function. Company name is available in the model.
 jQuery(document).ready(function () {
          var CompanyName =  @Model.Company;
}

Open in new window

When the @Model.Company is any number, for example "1111" then it works fine. But when it is coming as string like "TestCompany" I am getting the error  " Uncaught ReferenceError: TestCompany is not defined" .

Any suggestion what I am doing wrong?

Thanks in advance!
0
I have a sweetalert and want to format the text message with line breaks.
https://github.com/t4t5/sweetalert

The JavaScript for the Sweet alert is:

this.ArchiveLocation = function (id, url) {
        var text = "This will Archive the Location you have chosen.  Text here.... Click Cancel if you are unsure!"
        swal({
            title: "Archive Location?",
            text: text,
            showCancelButton: true,
            buttons: true,
            icon: "warning",
            dangerMode: true,
            closeOnConfirm: false,
            confirmButtonText: "Yes"
        },
            function () {
                general.post(url, {
                    id: id
                }, function () {
                    swal({
                        title: "Location Archived",
                        text: "Your Location was Archived.",
                        type: "success"
                    },
                        function () {
                            var url = $("#RedirectTo").val();
                            location.href = url;
                        }
                    );
                }.bind(this));
            }.bind(this));
    };

Open in new window


Basically, I need to format the text variable.
0
Amazon Web Services
LVL 19
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

I have a View using a Grouped DataTable like this:

@model List<master.Models.tbl_Data>


<table class="DTStyle filteredgroupedtable_14">
    <thead>
        <tr>
            <th>
                Field 2
            </th>
            <th>
               Field 1
            </th>
            <th>
                Field 3
            </th>
            <th>
               Field 4
            </th>
            <th>
                Field 5
            </th>
            <th>
               Field 6
            </th>
            <th>
               Field 7
            </th>
            <th>
                Field 8
            </th>
            <th>
                Field 9
            </th>
            <th>
               Field 10
            </th>
            <th>
                Field 11
            </th>
            <th>
               Field 12
            </th>
            <th>
                Field 13
            </th>
                    </tr>
    </thead>
    <tbody>
        @for (int j = 0; j < Model.Count; j++)
        {
            <tr>
                <td>
                  @Model[j].Field2
                </td>
                <td>
                    @Model[j].Field1
                </td>
                <td>
                    @Model[j].Field3
                </td>
                <td>
                    @Model[j].Field4
                </td>
                <td>
                    @Model[j].Field5
                </td>
                <td>
                    

Open in new window

0
I have two text boxes where user can select dates, then click the submit button to populate a webgrid, this works, but when I click on the sort or the filter the dates in the texboxes are not passed back and reset to current date - how can I keep the dates so I can utilize the sort, filters.

here is the code i am using

VIEW
@model IGrid<rptEODTelco>


@{
    ViewData["Title"] = "EOD Telco Summary";

}

<head>
    <link href="~/css/mvc-grid/mvc-grid.css" rel="stylesheet">
</head>

<div class="col-md-12">
    <div class="form-group">
        <form action="/Reports/EODTelcoSummary" method="post">
            <label for="StartDate">Start Date:</label>
            <input type="date" name="StartDate" value="@ViewBag.StartDate" />
            <label for="EndDate">End Date:</label>
            <input type="date" name="EndDate" value="@ViewBag.EndDate" />
            <button type="submit">Submit</button>
        </form>
    </div>
</div>

<div class="col-md-12">
    <div class="panel panel-primary list-panel">
        <div class="panel-heading list-panel-heading">
            <table align="center" width="100%">
                <tr>
                    <td align="center" colspan="2"><span style="font-size:28px;">EOD Telco Summary</span></td>
                </tr>
            </table>

        </div>
    </div>
    <div class="class=" panel-body">
        @(new HtmlGrid<rptEODTelco>(Html, Model))
    </div>
</div>

<script src="~/js/mvc-grid/mvc-grid.js"></script>
<script>

Open in new window

0
I have a table in my View.  I want the user to be able to click on a link to view related information in a modal.  I need help implementing this.  

My View just loops thru a list displaying those in a table:

 <tbody>
            @for (int j = 0; j < Model.Count; j++)
            {
                <tr>
                    <td>
                                INSERT LINK TO MODAL HERE FOR  @Model[j].Name
                    </td>
                    <td>
                        @Model[j].Field2
                    </td>
                    <td>
                        @Model[j].Field3
                    </td>
</tr>
 </tbody>

Open in new window

0
I have a form with multiple Text fields.  I need to check when the user completes the form if all of the fields match an entry already in the database.  If so, return a message and send them back to another View - perhaps the one matching their entry.  

Here is my form:  I have several more fields but just included a few as an example

    @using (Html.BeginForm("Add", "MyController", FormMethod.Post, new
    {
        name = "NewForm"
    }))
    {

        <div class="panel panel-info" style="position: relative;">
            <div class="panel-heading">Add Information</div>
            <div class="panel-body">
                <div class="col-xs-12">

                    <div class="row" style="margin-top: 0; margin-bottom: 5px;">
                        <div class="col-xs-6">
                            <div style="color:red;padding-bottom:0px; display:inline">*</div>
                            @Html.Label("Select Field 1")

                        </div>
                    </div>
                    <div class="row" style="margin-top: 0; margin-bottom: 10px;">

                        <div class="col-xs-6">

                            @Html.DropDownListFor(x => x.field1, sl.getField1List(), new
                       {
                           @type = "drop",
                           @id = "field1",
                       })
                            <div class="error">
                                @Html.ValidationMessageFor(x => x.field1)
          

Open in new window

0
I need to add grouping to this method:

[HttpPost]
        public JsonResult GetData(string variable1, string variable2, string variable3)
        {
            string[] reportData = (from x in DB.GetDetails().ToList()
                            where x.field1 == variable1
                            && x.field2 == variable2
                            && x.field3 == variable3
                            select x.field4).ToArray();

            return Json(new { option = reportData });
        }

Open in new window


I get duplicate values and need to group the data or add a Distince to the reportData.  I'm not sure how to go about this.  Thanks for any help!
0
I am a newbie to C# and have inherited a web app that I am now solely responsible for fixing and enhancing. I just created a Controller and a view via the VS wizard "MVC 5 Controller with views, using Entity Framework". I am using the default code that VS generated.

I also noticed that the record still comes up even if the ID is the same one as in the SQL View.

Any help would be greatly appreciated!

I have tried to start over and build everything a second time.

This is the controller.
public ActionResult Index(int? id)
{
 
if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); }
ViewBag.ID = id;
return View(db.JD.Where(x=>x.ID ==id).ToList());
}

This is the index.cshtml code
@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.JudgmentID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LoanID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.JudgmentAmount)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.JudgmentDate)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
            @Html.ActionLink("Details", "Details", new { id = item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.ID })
        </td>
    </tr>
}
This is what is displayed. There are actually 3 different records it …
0

.NET MVC

385

Solutions

291

Contributors

Microsoft’s ASP.NET MVC is a web application framework that implements the model–view–controller (MVC) pattern. As an open-source software, it’s set apart from the ASP.NET Web Forms component, which is proprietary.

Top Experts In
.NET MVC
<
Monthly
>