开发者

MVC3 Display a dropdown list from one datasource and save to another datasource

I'm getting back to an MVC3 project after a 3 month hiatus. I need to display a drop down list that pull开发者_如何学JAVAs from Database A, but saves to Database B. The property I need to persist is the NAICS/SIC code. Right now I just provide the user a text box to key in freeform text. So, I have the mechanics of that down. But instead it should provide only a valid list of codes from a source database.

The tricky thing to is I'm using a custom model binder to generate my ViewModels on the fly, so I don't have a distinct .cshtml file to customize.

[Serializable]
    public class Step4ViewModel : IStepViewModel
    {
        public Step4ViewModel()
        {


        }


        //load naics codes from somewhere

        [Display(Name = "Describe the nature of your business.")]
        public String NatureOfBusiness { get; set; }


        [Display(Name="NAICS/SIC CODE")]
        public String BusinessTypeCode { get; set; }

Tricky ViewModel

@using Microsoft.Web.Mvc;
@using Tangible.Models;

@model Tangible.Models.WizardViewModel 

@{ 
    var currentStep = Model.Steps[Model.CurrentStepIndex];
    var progress = ((Double)(Model.CurrentStepIndex) / Model.Steps.Count) * 100;
} 
<script type="text/javascript">
    $(function () {
        $("#progressbar").progressbar({
            value: @progress
        });
    });

</script> 

<div id="progressbar" style="height:20px;">
<span style="position:absolute;line-height:1.2em; margin-left:10px;">Step @(Model.CurrentStepIndex + 1) out of @Model.Steps.Count</span> 
</div>
    @Html.ValidationSummary()
@using (Html.BeginForm())
{ 


    @Html.Serialize("wizard", Model) 

    @Html.Hidden("StepType", Model.Steps[Model.CurrentStepIndex].GetType()) 


    @Html.EditorFor(x => currentStep, null, "") 



    if (Model.CurrentStepIndex > 0)
    { 
        <input type="submit" value="Previous" name="prev" /> 
    }

    if (Model.CurrentStepIndex < Model.Steps.Count - 1)
    { 
        <input type="submit" value="Save &amp; Continue" name="next"  /> 
    }
    else
    { 
        <input type="submit" value="Finish" name="finish" /> 
    }

         @*<input type="submit" value="Save" name="Save" />*@
}

Controller

[HttpPost]
        public ActionResult Index([Deserialize] WizardViewModel wizard, IStepViewModel step)
        {


            wizard.Steps[wizard.CurrentStepIndex] = step;
            if (ModelState.IsValid)
            {

                    //Always save.
                    var obj = new dr405();

                    //wire up to domain model;
                    foreach (var s in wizard.Steps)
                    {
                        Mapper.Map(s,obj,s.GetType(), typeof(dr405));
                    }

                    using (var service = new DR405Service())
                    {
                        //Do something with a service here.
                        service.Save(db, obj);
                    }


                if (!string.IsNullOrEmpty(Request["next"]))
                {
                    wizard.CurrentStepIndex++;
                }
                else if (!string.IsNullOrEmpty(Request["prev"]))
                {
                    wizard.CurrentStepIndex--;
                }
                else
                {
                    return View("Upload", obj);

                }
            }
            else if (!string.IsNullOrEmpty(Request["prev"]))
            {
                wizard.CurrentStepIndex--;
            }

            return View(wizard);


        }

WizardViewModel

 [Serializable]
    public class WizardViewModel
    {

        public String AccountNumber { get; set; }
        public int CurrentStepIndex { get; set; }
        public Boolean IsInitialized { get { return _isInitialized; } }

        public IList<IStepViewModel> Steps { get; set; }

        private Boolean _isInitialized = false;

        public void Initialize()
        {
            try
            {
                Steps = typeof(IStepViewModel)
                    .Assembly.GetTypes().Where(t => !t.IsAbstract && typeof(IStepViewModel).IsAssignableFrom(t)).Select(t => (IStepViewModel)Activator.CreateInstance(t)).ToList();
                _isInitialized = true;
                //rewrite this.  get the profile and wire them up or something.
                this.AccountNumber = Tangible.Profiles.DR405Profile.CurrentUser.TangiblePropertyId;

            }
            catch (Exception e)
            {

                _isInitialized = false;
            }
        }
    }


You can specify a template for a specific property on your view model by adding the UIHint attribute to the field. Since your view calls EditorFor on the model it will use the template you specified with UIHint.

BusinessTypeDropdown.ascx - (placed in Views/Shared/EditorTemplates

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<% var businessTypes = ViewData["businessTypes"] as IEnumerable<string>; %>
<%= Html.DropDownListFor(m => m , new SelectList(businessTypes, Model))%>

In your View Model

[Serializable]
public class Step4ViewModel : IStepViewModel
{
    public Step4ViewModel()
    {


    }


    //load naics codes from somewhere

    [Display(Name = "Describe the nature of your business.")]
    public String NatureOfBusiness { get; set; }


    [Display(Name="NAICS/SIC CODE")][UIHint("BusinessTypeDropdown")]
    public String BusinessTypeCode { get; set; }

Then in your controller just set ViewData["businessTypes"] to your list of business types.


Without understanding your "tricky" view model code, it will be hard to make helpful suggestions.

However, there shouldn't be much problem here. You need to somehow create your dropdown list in yoru view, and populate it from data passed from your controller.

All the work happens in your controller. Populate your list or IEnumerable or whatever data source from your first database, then in your post handler save the selection it to your second database (the second part should not be much different from what you already have).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜