简体   繁体   中英

ASP.NET MVC Control

I have this code repeated many times in my page

<div>
  <span>text</span><br />
  <span>text1</span><select></select><span>text2</span>
  <input/>                  
</div>

I dont want to write it every time how can i box it in MVC and pass parameters to it?

you could create an HTML helper that returns that HTML

something like the below:

using System;
namespace MvcApplication1.Helpers
{
          public class LabelHelper

          {
               public static string Label(string target, string text)
               {
                    return String.Format("<label for='{0}'>{1}</label>", target, text);
               }
          }
}

You can create partial view and have a ViewModel which has all those information which you are showing. Wherever you want to use this content, call the partial view with the ViewModel.

@model MyBoxContent
<div>
  <span>@Model.Text1</span><br />
  <span>@Model.Text1</span><select></select><span>@Model.Text2</span>
  <input/>                  
</div>

and have a view model called "MyBoxContent"

 public class MyBoxContent
 {
        public string Text1{ set; get; }
        public string Text2{ set; get; }
 }

Have this ViewModel as the property of your other ViewModel from where you want to show and call the Partial View with that.

 @Html.Partial("BoxData", Model.MyBoxContent);

So you can use a partialView and just render it.

@Html.Partial("SomePartialView", DataYouPlanOnPassingIn)

also don't forget to put your model at the top of the partial view so you can start using it:

@model System.String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM