.NET MVC

373

Solutions

282

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

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
Python 3 Fundamentals
LVL 13
Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

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
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
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
Should you be charging more for IT Services?
Should you be charging more for IT Services?

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!

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
Hi all,

We have an ASP.NET MVC application that has a partial page containing a select list, when the value of that select list is changed, we use JavaScript to populate a second select list.

After this happens we attempt to get the first value from the second select list, but there are no options for it. If we do a console.log output, we can see the second select list has it's new options, but the options.length property shows as zero. It is as if JavaScript sees it as a string of HTML and not an array of values.

Has anyone encountered this before and if so, how did you resolve the issue?

Thank you.

resourcesys.
0
We have a Asp.net core restAPI hosted on windows Azure.
Now we are looking cloud based logging service which we can use for the api hosted on azure.

If any service are there please let us know.
0
On my machine my MVC5 Razor application opens just fine. When I move it to a different server and try to open the application I get a page telling me: "This page cannot be displayed". I'm new to MVC/Razor so please bare with. I will give what code I have. So...

My RouteConfig.cs file looks like this:
namespace MyApplication
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
	            "Default",
	            "{controller}/{action}/{credentialsGUID}",
	            new
	            {
		            controller = "Manager",
		            action = "Index",
		            credentialsGUID = UrlParameter.Optional
	            },
	            new { credentialsGUID = new IntranetUserGUID() }
            );

			routes.MapRoute(
                "AddEditGroup",
                "{controller}/{action}/{id}",
                new
                {
                    controller = "Manager",
                    action = "AddEditGroup",
                    id = UrlParameter.Optional
                }
            );

            routes.MapRoute(
	            name: "ErrorOccurred",
	            url: "{controller}/{action}/{id}",
	            defaults: new { controller = "Errors", action = "ErrorOccurred", id = UrlParameter.Optional }
            );

			//RegisterErrorHandlingRoute.Register(routes, "Errors");
		}
    }
}

Open in new window



My Index cshtml page looks like this (partially)

@using ServiceGroupManagement.Resources
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
    string strSpacer = "&nbsp;&nbsp;";
}

@using (Html.BeginForm("GroupLanding", "Manager", FormMethod.Post))
{
.
.
.
}

Open in new window


I only have 1 manager and below is part of the code, that I think is relevant here.:
namespace MyTool.Controllers
{
	public class ManagerController : ControllerBase
	{
		
		[AllowAnonymous]
		public override RedirectToRouteResult Index(Guid credentialsGUID)
		{
			SetUserPrincipal(credentialsGUID);

			return RedirectToAction(ActionNameAfterAuthentication, new FormCollection());
		}

		public ActionResult GroupLanding(FormCollection collection)
		{
                  .
                  .
                  .
                }
.
.
.

		protected override string ActionNameAfterAuthentication
		{
			get { return "GroupLanding"; }
		}

Open in new window


Again, on my local machine this works fine. On a different server it doesn't even make it to my index view before it tell me: "This page can't be displayed." I'm checking the Even Viewer on the server where it is blowing up, but as of right now I'm not %100 sure if any of the events I see are related. Once/if I am, I will post. Pleas help? Thank you.
0
Hi all,

We are building an MVC website, and we would like to include some legacy functionality from a WebForms site.

So, we have our MVC view and we can load a webform into a DIV on the page, but when we post the webform, it goes to an incorrect url.

We have tried setting the postbackurl property of a button on the webform but this makes no difference.

Has anyone tried to do something similar before, and if so, did you have any success?

Is this even possible?

Any advice is much appreciated.

resourcesys.
0
<button class="btn btn-xs" ng-click="dateRangeSelectionBox.submit()" ng-disabled="!showText">Submit</button>

The button works correctly on click. How to make it work the same on hitting ENTER?

Thanks.
0
Introduction to Web Design
LVL 13
Introduction to Web Design

Develop a strong foundation and understanding of web design by learning HTML, CSS, and additional tools to help you develop your own website.

On my home controller I have this action result.

        public ActionResult Maths()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

Open in new window


I have a view called maths with a button it.  

@Html.TextBox("name")
<input id="cmdCount" type="button" value="Count up to chosen number. and print to a text file." />

Open in new window


When I press the button I want it to find the prime numbers up to the number I enter in a text box using this code.
I'm not sure how to pass the value I enter in the textbox back to the controller after pressing the button.

I will want to be able to add other buttons on the same page (view) to perform other mathematical functions eg finding Pythagrean triples.  I have the code to find the triples, but don't know how to structure the view and controller.

using System;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApp5
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            PrintList(int.Parse(txtPrimes.Text));
        }
        public void PrintList(int MaxNumberToTry)
        {
            try
            {
                using (StreamWriter sw = new StreamWriter(@"D:\OneDrive\Documents\MyPrograms\MathsPrograms\Prime1.csv", false))
                {
                    int CheckThisNumber = 2;
             

Open in new window

0
I have the following codes to make a simple http get call, and if the call is success, it is supposed to return like https://www.api.com?status=success
In my class library, I have the following codes, how can I get status value?
Because I have the codes in the class library, I can't call request.querystring, and I have no idea what to do.



 
public Domain.CardResponse CreditCardOneTimePurchaseRequest(CardRequest request)
        {             
            #region Build data string
            StringBuilder sb = new StringBuilder();
            sb.Append(             
                param.serviceName + equalSign + request.serviceName + ampersandSign +
                param.ID + equalSign + request.ID + ampersandSign                
                );
            #endregion
            #region Request
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var requestCall = (HttpWebRequest)WebRequest.Create(sb.ToString());
            #endregion
            #region Response
            Domain.Associ.ApiResponse response = new Domain.Realty.Associ.CardResponse();
            var responseCall = (HttpWebResponse)requestCall.GetResponse();
            var responseString = new StreamReader(responseCall.GetResponseStream()).ReadToEnd();

            //if (responseString.Contains(successInText))
            //{
            //returnStr = successInText;            
                

Open in new window

0
we use PayPal credit card reader with our iPhone for events.

we want to know how the reader works with sdk. e g. when the credit card is scanned, can it pass the data to the web form mvc page that we built.
0
Hi

I am trying to work with a Visual Studio solution that was developed for Xero accounting software's API.
In the image you see the project explorer with the Xero.Api.Example.MVC is the startup project.
I want to add a webform where I can try to POST an invoice to the API. Where do I do that?
I have experience developing ASP.net VB.net webforms so am a little lost here and just need some advice
on where I can build webforms to build functionality in
1
0
I also want to create my own super simple membership website for my personal usage.
let us assume the db table called role has two roles, admin, user. if I want to restrict the controllers (mvc) base on the roles.
how can I do that?

[role = admin]
Controller HIAdmin
[role = user]
Controller HiUser
0
I want to use MVC identity 2.0 with my new project. However, I think it is over-kill what I need. and I want to have super simple way to handle login/password and other simple requirements i have. so I have the following list and it is my requirement. I just need very basic membership security.

1. Each controller have a way to reflect base on the roles (admin, buyer, seller and etc.)
2. No need for any external single sign on such as facebook
3. Flexible way to add security question for member profile
4. all data stores in MS SQL, not app data / table database.

Thanks
0

.NET MVC

373

Solutions

282

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.