Modify DropDownList MVC using Users?

0

I have these models in my users, febriles, districts and services, users and febriles data is required for districts and services, I have a dropdownlist with the following jquery and json script:

@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
   $(document).ready(function () {
       $("#DistrictId").change(function () {
           $("#ServiceId").empty();
           $.ajax({
               type: 'POST',
               url: '@Url.Action("GetServices")',
               dataType: 'json',
               data: { districtId: $("#DistrictId").val() },
               success: function (districts) {
                   $.each(districts, function (i, service) {
                       $("#ServiceId").append('<option value="'
                           + service.ServiceId + '">'
                           + service.Name + '</option>');
                   });
               },
               error: function (ex) {
                   alert('Failed to retrieve services.' + ex);
               }
           });
           return false;
       })
   });
</script>

In the febrile driver I have this method to get the services of the jquery:

  public JsonResult GetServices(int districtId)
    {
        db.Configuration.ProxyCreationEnabled = false;
        var services = db.Services.Where(s => s.DistrictId == districtId).OrderBy(s => s.Name);
        return Json(services);
    }

And in my view create of febriles I have this:

@model Fevers.Models.Fever

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Fever</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.DistrictId, "District", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("DistrictId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.DistrictId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ServiceId, "Service", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("ServiceId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.ServiceId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.QuantityPatients, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.QuantityPatients, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.QuantityPatients, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.QuantityFevers, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.QuantityFevers, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.QuantityFevers, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}
<div>
  @Html.ActionLink("Back to List", "Index")
</div>

What I want to do is that after entering a user and it is logged in, only the services of the district to which the user belongs are loaded.

    
asked by SELSO ALONSO 22.11.2018 в 02:00
source

2 answers

2

If you are going to use $.ajax the @Html.DropDownList is not used since you would not send the data as part of the model but you will recover it using ajax and json

<select id="ServiceId" class="form-control"> 
</select>

by just defining the html it reaches so that when the $ .ajax is executed and you define the options

Perhaps an important point is the load of the combo in the load of the page if the combo District has a default option

<script type="text/javascript">

   $(function () {

       $("#DistrictId").change(function () {
           LoadService();
       })

       LoadService();
   });

   function LoadService(){
        $("#ServiceId").empty();
        $.ajax({
           type: 'POST',
           url: '@Url.Action("GetServices")',
           dataType: 'json',
           data: { districtId: $("#DistrictId").val() },
           success: function (districts) {
               $.each(districts, function (i, service) {
                   $("#ServiceId").append('<option value="'
                       + service.ServiceId + '">'
                       + service.Name + '</option>');
               });
           },
           error: function (ex) {
               alert('Failed to retrieve services.' + ex);
           }
        });
   }
</script>
    
answered by 22.11.2018 в 13:38
1

If your question is; What I want to do is that after entering a user and it is logged in, only the services of the district to which the user belongs are loaded.

The answer is as follows:

First: You must make a relation between the tables of your Data Base and the IdentityUser tables, specifically the ApplicationUser table. The idea is that when the user after login with a query in this way

var estaAutentificado = User.Identity.IsAuthenticated; // verifica si esta autentificado el usaurio, devuelde un Boolean
if (estaAutentificado)
{
 var idUsuario = User.Identity.GetUserId(); // Obtiene el id del usuario
}

Second: you must make a query in your GetServices method, similar to this, using the navigation properties:

var services = db.Users.Where(x => x.Id == idUsuario ).Include(x => x.Services).ToList();

If you have any questions, you can ask. Thanks !!

    
answered by 24.11.2018 в 18:41