Rectangle 27 7

Using in project

  • Blender to create 3D models. (You can use Maya or 3D Max, I will tell you how to export the model for Blender, same works for 3D Max and Maya).
  • PVRGeoPOD blender extension from Imagination Technology to convert blender model to format that Cocos3D understand. You can see that the link downloads an installer file which in turns downloads the entire SDK. I can't see an easy way to download the blender extension alone.

Cocos3D is written on top of popular Cocos2D, a popular 2D game framework. Important think to note here is that, Cocos2D 2.x version is already there and stable. But Cocos3D works with Cocos2d 1.x version only.

When you unzip the source you downloaded you will find a README file inside and it specifically says,

The README file clearly tells the installation procedure. After installation, you will get a nice Cocos3D project template in XCode.

This requires some explanation. When you run the PVRGeoPOD installer, a screen shows what and what features need to be installed. I only selected

You can install other tools in the list, but I only used these two.

Now after the installation process (which may take some time), you need to add the PVRGeoPOD AddOn to blender. You can find the PVRGeoPOD.UserManual.PDF file in the just installed folder, which also contains below information.

  • Find Blender Add-On folder, you can open blender python console and run command bpy.utils.script_paths("addons") to see the path to this folder.
  • Find the blender add-on files inside the PVRGeoPOD folder, in your installation path. When you see files like libPVRGeoPOD.dylib and PVRGeoPODScript.py and 2 QTfiles, stop there as this is the location. Copy these 4 files and paste them in blender add on folder.
  • Now open blender, choose Preferences, find Add-On tab, search and find PVRGeoPOD extension and enable it by clicking the checkbox on the right.
  • Now Quit and restart blender, if needed, and select file->export and see if there is an option called PVRGeoPOD(.pod/.h/.cpp), if yes,you are successful.

Now you can create models in blender, and export these models as .POD files which Cocos3D understands.

If you are using other 3D designing tools like Maya, 3D Max, this PVRGeoPOD extension can be added to them also. Just see the PDF I mentioned above.

Create your model in blender (.blend) and export it as .POD file. When you export I normally select following options

and rest I left it as default.

  • Create a new project in XCode, choose Cocos3D template.
  • Add the .POD files to your project. If yours a textured model, add that texture to your project also.

The template project itself contains a HelloWorld.POD file, you can replace that line with your .POD file so that your model will be visible.

[self addContentFromPODFile: @"YourPODFileName.pod"];

Now you have your first 3D model visible in iOS device.

ios - Want to display a 3D model on the iPhone: how to get started? - ...

iphone ios opengl-es
Rectangle 27 9

Create a model

Without using [FromURI] (POST requests with query strings?), how can I make POSTs of multiple parameters or complex objects without converting these parameters into a single POCO class?

I know its not what you want to hear but out of the box this is not possible. It is not a limitation of the browser code that is making the request. This means it does not matter if you are using Angular, JQuery, straight JavaScript, or even RestangularJS. This is a limitation (I use that word loosely as I am sure this is by design) of Web API (any version). Here is the documentation on this design: Parameter Binding in ASP.NET Web API by Mike Wasson.

At most one parameter is allowed to read from the message body. So this will not work:

// Caution: Will not work!
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

So the question becomes, what are your options?

This is the thing you were trying to avoid but I list it first because this is how Web API was intended to behave. I have not yet heard a compelling reason not to do this. This approach allows you to extend your model easily without having to change the method signature. It also allows for model validation on the model itself. Personally I really like this approach.

public class SignInModel{
    public string Email {get;set;}
    public string Password {get;set;}
}

[HttpPost]
[Route("signin")]
public async Task<IActionResult> Signin(SignInModel signInModel)
{
       // ....
}

Again, what you were trying to avoid. This does make what you want possible with the limitation that you have to pass these parameters using the Query string on the URL. The JavaScript would change but the signature you had on the Web API method would not.

public signin(inputEmail: string, inputPassword: string): Observable<Response> {
    return this.http.post('/api/account/signin/?email=inputEmail&password=inputPassword', null, this.options);
}

See Passing multiple POST parameters to Web API Controller Methods by Rick Strahl. This option allows you to create a custom model binder that could do what you are asking. It is a whole bunch of extra code though for, IMHO, not much benefit. Maybe there are situations where it would be useful although I really cannot think of any off the top of my head.

Finally you could also pass in a dynamic object as the parameter of your Web API. This is essentially the same as receiving the JSON as a string and making your Controller code responsible for the deserialization of content. Again, I believe that this would make your code worse in most situations as you have to implement custom validation and type checks. This answer was proposed previously on SO by Bes Ley. Again, maybe there are situations where it would be useful although I really cannot think of any off the top of my head.

This is on spot. Regardless of which javascript framework your using they all uses the same protocol (http) which has its rules and limitations.

Angular2 HTTP Post ASP.NET MVC Web API - Stack Overflow

asp.net asp.net-web-api angular asp.net-web-api2 restangular
Rectangle 27 2

Using the @model tag is actually a shortcut for the @inherits tag.

You specify the class, your generated class will inherit from from the class specified with @inherits.

@inherits MyTemplate<MyModel>
class MyTemplate<T> {
    public T Model { get; set; }

    public abstract void Execute();
    public virtual void Write(object value) {
        WriteLiteral(value);
    }

    public virtual void WriteLiteral(object value) {
        // Actual writing goes here
    }

}

The result from the razor parsing, you need to compile, and create an instance from.

After you created the instance you can set the Model property, and call Execute to generate the result, how and what you generate is up to you.

Thanks, works like a charm. :)

asp.net mvc 3 - Hosting the Razor View Engine using a view model - Sta...

asp.net-mvc-3 razor
Rectangle 27 2

Using the @model tag is actually a shortcut for the @inherits tag.

You specify the class, your generated class will inherit from from the class specified with @inherits.

@inherits MyTemplate<MyModel>
class MyTemplate<T> {
    public T Model { get; set; }

    public abstract void Execute();
    public virtual void Write(object value) {
        WriteLiteral(value);
    }

    public virtual void WriteLiteral(object value) {
        // Actual writing goes here
    }

}

The result from the razor parsing, you need to compile, and create an instance from.

After you created the instance you can set the Model property, and call Execute to generate the result, how and what you generate is up to you.

Thanks, works like a charm. :)

asp.net mvc 3 - Hosting the Razor View Engine using a view model - Sta...

asp.net-mvc-3 razor
Rectangle 27 16

Here's another approach using a model method. This version resolves picklist/choice fields, skips empty fields, and lets you exclude specific fields.

def get_all_fields(self):
    """Returns a list of all field names on the instance."""
    fields = []
    for f in self._meta.fields:

        fname = f.name        
        # resolve picklists/choices, with get_xyz_display() function
        get_choice = 'get_'+fname+'_display'
        if hasattr( self, get_choice):
            value = getattr( self, get_choice)()
        else:
            try :
                value = getattr(self, fname)
            except AttributeError:
                value = None

        # only display fields with values and skip some fields entirely
        if f.editable and value and f.name not in ('id', 'status', 'workshop', 'user', 'complete') :

            fields.append(
              {
               'label':f.verbose_name, 
               'name':f.name, 
               'value':value,
              }
            )
    return fields

Then in your template:

{% for f in app.get_all_fields %}
    <dt>{{f.label|capfirst}}</dt>
        <dd>
            {{f.value|escape|urlize|linebreaks}}
        </dd>
{% endfor %}
except User.DoesNotExist:

I would be inclined to use AttributeError instead of User.DoesNotExist - I can't see why it would throw User.DoesNotExist.

Also, might be better to use self._meta.get_fields() as this is officially exposed in django 1.8+. However, then you end up with relations in the code, which you'd have to filter out by checking f.is_relation

I've edited the answer to use AttributeError instead of User.DoesNotExist (which was a leftover from my original implementation). Thanks. I'm holding off on _meta.get_fields() until I can test it.

python - Iterate over model instance field names and values in templat...

python django django-templates
Rectangle 27 13

Unfortunately simple_form relies on using a model. Essentially it would be nice to have something like simple_form_tag and input_tag methods equivalent to their rails *_tag helpers. Until then, there's an easy work around.

Use a symbol instead of the class in the form and pass the value explicitly to prevent simple_form from trying to access the model properties.

<%= simple_form_for :user, :url => '/users' do |f| %>
  <%= f.text_field :name, input_html: { value: nil } %>
<% end %>
undefined method 'name' for User
selected
value
undefined method 'name' for Model

ruby on rails - SimpleForm without for (non model form) - Stack Overfl...

ruby-on-rails ruby-on-rails-3 simple-form
Rectangle 27 13

Unfortunately simple_form relies on using a model. Essentially it would be nice to have something like simple_form_tag and input_tag methods equivalent to their rails *_tag helpers. Until then, there's an easy work around.

Use a symbol instead of the class in the form and pass the value explicitly to prevent simple_form from trying to access the model properties.

<%= simple_form_for :user, :url => '/users' do |f| %>
  <%= f.text_field :name, input_html: { value: nil } %>
<% end %>
undefined method 'name' for User
selected
value
undefined method 'name' for Model

ruby on rails - SimpleForm without for (non model form) - Stack Overfl...

ruby-on-rails ruby-on-rails-3 simple-form
Rectangle 27 2

Have you thought about using an Observer? That way you can keep the after_commit stuff, which does not appear to to belong in the model, in its proper place. Plus it helps simplify your model instead of cluttering it up.

For the syntax error, self is a reserved word. Rename the variable name in the method declaration. So try something like:

def twitter_share(post)
  # do stuff
end

To access the url helpers outside of the controller, use:

Rails.application.routes.url_helpers.post_url(@post, :host => 'myhost.com')

Don't forget to use the :host option when accessing the url helpers outside the controller so the helper has context.

Hi, thanks for the help. I am trying to get the code above working but am running into some problems, namely when I add the Rails.application.routes... my destroy action fails and says there's no route. I've edit above to show whats happening.

sorry, I don't see the edit you have mentioned.

Hehe sorry I posted the edit after that comment :)

Rails.application.routes.url_helpers.post_url(@post, :host => 'myhost.com' returns the url to the post specified by @post as a string. That should go inside the method where you need the url. My guess is inside twitter_share.

Hmm im still getting the error No route matches {:action=>"destroy", :controller=>"posts"} when using the Rails.applications.routes.url_helpers code, any ideas?

Rails: How to pass parameters from a model using an after_commit metho...

ruby-on-rails ruby-on-rails-3 activerecord parameter-passing
Rectangle 27 9

1) Use fluent validation on the model that the retrieves information from the user. it is more flexible then data annotation and easier to test.

2) You might want to look into automapper, by using automapper you don't have to write x.name = y.name.

Everything below is based on the new information

First and all you should place validation on both location like you did now for the actual model validation this is how I would do it. Disclaimer: this is not the perfect way

First and all update the UserViewModel to

public class UserViewModel
    {
        [Required()]
        [RegularExpression(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$")]
        public String Email { get; set; }
    }
// Post action
        [HttpPost]
        public ActionResult register (UserViewModel uvm)
        {
            // This validates the UserViewModel
            if (ModelState.IsValid)
            {

                try
                {
                    // You should delegate this task to a service but to keep it simple we do it here
                    User u = new User() { Email = uvm.Email, Created = DateTime.Now };
                    RedirectToAction("Index"); // On success you go to other page right?
                }
                catch (Exception x)
                {
                    ModelState.AddModelError("RegistrationError", x); // Replace x with your error message
                }

            }       

            // Return your UserViewModel to the view if something happened               
            return View(uvm);
        }

Now for the user model it gets tricky and you have many possible solutions. The solution I came up with (probably not the best) is the following:

public class User
    {
        private string email;
        private DateTime created;

        public string Email
        {
            get
            {
                return email;
            }
            set
            {
                email = ValidateEmail(value);
            }
        }

        private string ValidateEmail(string value)
        {
            if (!validEmail(value))
                throw new NotSupportedException("Not a valid email address");     

            return value;
        }

        private bool validEmail(string value)
        {
            return Regex.IsMatch(value, @"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$");
        }
[TestClass()]
    public class UserTest
    {

        /// <summary>
        /// If the email is valid it is stored in the private container
        /// </summary>
        [TestMethod()]
        public void UserEmailGetsValidated()
        {
            User x = new User();
            x.Email = "test@test.com";
            Assert.AreEqual("test@test.com", x.Email);
        }

        /// <summary>
        /// If the email is invalid it is not stored and an error is thrown in this application
        /// </summary>
        [TestMethod()]
        [ExpectedException(typeof(NotSupportedException))]
        public void UserEmailPropertyThrowsErrorWhenInvalidEmail()    
       {
           User x = new User();
           x.Email = "blah blah blah";
           Assert.AreNotEqual("blah blah blah", x.Email);
       }


        /// <summary>
        /// Clears an assumption that on object creation the email is validated when its set
        /// </summary>
        [TestMethod()]
        public void UserGetsValidatedOnConstructionOfObject()
        {
            User x = new User() { Email = "test@test.com" };
            x.Email = "test@test.com";
            Assert.AreEqual("test@test.com", x.Email);
        }
    }

prd @Serghei I actually wanted to know how do I validate the model class (which is not bound to view). Keeping that my Views have properties from different model classes (in a ViewModel class) to fulfill all requirements on that particular View.

@Yahya Can you post an example? it will be easier to point out where you should, and how, to do the validation.

prd I have added sample code in the original question for you. I hope it makes sense now.

@Yahya i updated my post with a possible solution however its not the best one

prd Thanks for the solution. Unfortunately this doesn't look very tidy. For now, as my business entities are not mission critical, I am just living with no validation on them. Doing all the validation on viewmodels. For mapping, I took your advice and am using Automapper.

c# - Validation best practice for Model and ViewModel - Stack Overflow

c# asp.net-mvc-2 model viewmodel asp.net-mvc-2-validation
Rectangle 27 4

You should be using a Model, not the ViewBag, that's where your headache starts!

First let's create a model based on what you need:

public class MyModel
{
    public Manpower Manpower { get; set; }

    public SelectList Categories { get; set; }
    public SelectList MaritalStatuses { get; set; }
    public SelectList Religions { get; set; }
    public SelectList Languages { get; set; }

    //here's your Load Method to populate it
    public MyModel Load()
    {
        //load your Manpower object here
        Categories = new SelectList(db.Categories
            .OrderBy(x => x.Name)
            .ToList(), "Id", "Name");
        Countries = new SelectList(db.Countries
            .OrderBy(x => x.Name)
            .ToList(), "Id", "Name");
        MaritalStatuses = new SelectList(db.MaritalStatus
            .OrderBy(x => x.Name)
            .ToList(), "Id", "Name");
        Religions = new SelectList(db.Religions
            .OrderBy(x => x.Name)
            .ToList(), "Id", "Name");
        Languages = .new SelectList(db.Languages
            .OrderBy(x => x.Name)
            .ToList(), "Id", "Name");
    }
}

Now let's fix that get controller method:

[Authorize]        
public ActionResult Create()
{
    var model = new MyModel().Load();

    return View("~/Views/en/Create.cshtml", model);
}

Next, I'll show you sample view Code (format it appropriately), note that I'm assuming here that Manpower has all the possible fields:

@model MyModel //make sure this is the top line of your view

@Html.DropDownListFor(m => m.Manpower.CategoryId, m.Categories)
@Html.DropDownListFor(m => m.Manpower.MaritalStatusId, m.MaritalStatuses)
@Html.DropDownListFor(m => m.Manpower.ReligionId, m.Religions)
@Html.DropDownListFor(m => m.Manpower.EnglishId, m.Languages)
@Html.DropDownListFor(m => m.Manpower.ArabicId, m.Languages)

//your other Manpower object items here now....

Now in the Save method we can do:

[HttpPost]
[Authorize]
public ActionResult Create(MyModel model)
{
    if (ModelState.IsValid)
    {
        model.Manpower.CreatedBy = User.Identity.Name;
        model.Manpower.CreatedOn = DateTime.Now;
        db.Manpowers.AddObject(model.Manpower);
        db.SaveChanges();
        return RedirectToAction("AddImage", new { manpower.Id});  
    }

    return RedirectToAction("Create"); //not sure why you're going back to create though?
}

Dude where is the ViewBag ...? +1

c# - ModelState is Invalid for Drop Down List - Stack Overflow

c# asp.net-mvc asp.net-mvc-3 linq razor
Rectangle 27 63

Using TempData to pass model data to a redirect request in Asp.Net Cor...

RedirectToAction returns a 302 response to the client browser and thus the browser will make a new GET request to the url in the location header value of the response came to the browser.

If you are trying to pass a simple lean-flat view model to the second action method, you can use this overload of the RedirectToAction method.

protected internal RedirectToRouteResult RedirectToAction(
    string actionName,
    string controllerName,
    object routeValues
)

The RedirectToAction will convert the object passed(routeValues) to a query string and append that to the url(generated from the first 2 parameters we passed) and will embed the resulting url in the location header of the response.

public class StoreVm
{
    public int StoreId { get; set; }
    public string Name { get; set; }
    public string Code { set; get; } 
}

And you in your first action method, you can pass an object of this to the RedirectToAction method like this

var m = new Store { StoreId =101, Name = "Kroger", Code = "KRO"};
return RedirectToAction("Details","Store", m);

This code will send a 302 response to the browser with location header value as

Store/Details?StoreId=101&Name=Kroger&Code=KRO

Assuming your Details action method's parameter is of type StoreVm, the querystring param values will be properly mapped to the properties of the parameter.

public ActionResult Details(StoreVm model)
{
  // model.Name & model.Id will have values mapped from the request querystring
  // to do  : Return something. 
}

The above will work for passing small flat-lean view model. But if you want to pass a complex object, you should try to follow the PRG pattern.

PRG stands for POST - REDIRECT - GET. With this approach, you will issue a redirect response with a unique id in the querystring, using which the second GET action method can query the resource again and return something to the view.

int newStoreId=101;
return RedirectToAction("Details", "Store", new { storeId=newStoreId} );

This will create the url Store/Details?storeId=101 and in your Details GET action, using the storeId passed in, you will get/build the StoreVm object from somewhere (from a service or querying the database etc)

public ActionResult Details(string storeId)
{
   // from the storeId value, get the entity/object/resource
   var store = yourRepo.GetStore(storeId);
   if(store!=null)
   {
      // Map the the view model
      var storeVm = new StoreVm { Id=storeId, Name=store.Name,Code=store.Code};
      return View(storeVm);
   }
   return View("StoreNotFound"); // view to render when we get invalid store id
}

Following the PRG pattern is a better solution to handle this use case. But if you don't want to do that and really want to pass some complex data across Stateless HTTP requests, you may use some temporary storage mechanism like TempData

TempData["NewCustomer"] = model;
return RedirectToAction("Index", "Users");

And read it in your GET Action method again.

public ActionResult Index()
{      
  var model=TempData["NewCustomer"] as Customer
  return View(model);
}

TempData uses Session object behind the scene to store the data. But once the data is read the data is terminated.

you cannot pass complex types in TempData

string
int
Guid

If you absolutely want to pass a complex type object via TempData, you have 2 options.

1) Serialize your object to a string and pass that.

Here is a sample using Json.NET to serialize the object to a string

var s = Newtonsoft.Json.JsonConvert.SerializeObject(createUserVm);
TempData["newuser"] = s;
return RedirectToAction("Index", "Users");

Now in your Index action method, read this value from the TempData and deserialize it to your CreateUserViewModel class object.

2) Set a dictionary of simple types to TempData

var d = new Dictionary<string, string>
{
    ["FullName"] = rvm.FullName,
    ["Email"] = rvm.Email;
};
TempData["MyModelDict"] = d;
return RedirectToAction("Index", "Users");
public IActionResult Index()
{
   if (TempData["MyModelDict"] is Dictionary<string,string> dict)
   {
      var name = dict["Name"];
      var email =  dict["Email"];
   }
   // to do : return something
}

asp.net mvc - How do I include a model with a RedirectToAction? - Stac...

asp.net-mvc
Rectangle 27 12

Here is a quick example of using the ViewBag. I would recommend switching and using a model to do your binding. Here is a great article on it. Model Binding

public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        List<string> items = new List<string>();
        items.Add("Product1");
        items.Add("Product2");
        items.Add("Product3");

        ViewBag.Items = items;
        return View();
    }
[HttpPost]
    public ActionResult Index(FormCollection collection)
    {
        //only selected prodcuts will be in the collection
        foreach (var product in collection)
        {

        }
        return View();
    }
@using (Html.BeginForm("Index", "Home"))
 {
     foreach (var p in ViewBag.Items)
     {
        <label for="@p">@p</label>
        <input type="checkbox" name="@p" />
     }

    <div>
    <input id='btnSubmit' type="submit" value='submit' />
    </div>
 }

c# - MVC Pass ViewBag to Controller - Stack Overflow

c# asp.net-mvc model-view-controller razor viewbag
Rectangle 27 2

You shouldn't be using your model like this, just pass the items you need for the functions you require:

$this->load->model("user_crud");

$data['categories'] = $this->user_crud->get_categories($id, $category, $etc);

I would suggest (after seeing your code) that you study the fantastic codeigniter userguide as it has really good examples, and you just went a totally different way (treating model like an object). Its more simple sticking to how it was designed vs what you are doing.

CodeIgniter: How to pass variables to a model while loading - Stack Ov...

codeigniter variables model controller
Rectangle 27 30

For anyone who also likes how Jeffrey Way uses Model::create() in his Laracasts 5 tutorials, where he just sends the Request straight into the database without explicitly setting each field in the controller, and using the model's $fillable for mass assignment (very important, for anyone new and using this way): I read a lot of people using insertGetId() but unfortunately this does not respect the $fillable whitelist so you'll get errors with it trying to insert _token and anything that isn't a field in the database, end up setting things you want to filter, etc. That bummed me out, because I want to use mass assignment and overall write less code when possible. Fortunately Eloquent's create method just wraps the save method (what @xdazz cited above), so you can still pull the last created ID...

public function store() {

    $input = Request::all();
    $id = Company::create($input)->id;

    return redirect('company/'.$id);
}
$new = Company::create($input);
return redirect('company/'.$new->id);

Works as prescribed in 5.2. Thanks!

php - Laravel, get last insert id using Eloquent - Stack Overflow

php database laravel eloquent
Rectangle 27 3

If you don't want to render the input as described in your model, you probably don't want to be using the Html.TextBoxFor helper.

Try Html.TextBox instead. You can provide it with the exact values you're looking for:

@Html.TextBox("UserName", Model.Name, new { id = "UserName" })

Don't forget you can also forget the helpers and use plain old html:

<input id="UserName" name="UserName" type="text" value="@Model.Name" />

Warning: When using either of these methods and the default model binder, the value of this input will not be bound back to your model correctly when submitting back the data.

Could you please explain the "warning" part a little bit? Are form fields not already saved on postback in MVC?

Values are bound to models based on the input names. So in this case the model binder doesn't know that the value from the "UserName" input corresponds to the "Name" value on the model.

asp.net mvc 3 - When using Html.TextBoxFor, add the name of the model ...

asp.net-mvc-3 model-view-controller html-helper
Rectangle 27 5

The controller will create the viewmodel object and fill it out using the model. The model should use the ORM to get the data.

The ViewModel is always specific to the view only, and the model is specific to the domain. In CQRS you would actually just get the ViewModel and send it to the view.

From the controller you can do what ever it takes to make your CRUD happen for the view. If you use the Repo pattern thats ok, if you use NHibernate or EF directly thats cool tool. Once the ViewModel goes to the view it will be disconnected from everything like the DB, so fill it out before it gets there.

100% correct. The Model concept is a bit vague in the MVC definition and that's probably why the ViewModel was introduced in ASP.Net MVC. (I'm not saying that ms created the ViewModel concept, just that they made a pretty clear distinction between Model and ViewModel).

design - Who should be responsible for getting the data in MVC? - Stac...

design asp.net-mvc-3
Rectangle 27 6

Try passing a ViewModel into your page, and using the model binder to post the same view model back into your controller

public class MerchantModel
{
    public int AppId { get; set; }
    public string Name { get; set; }
    public bool IsSelected { get; set; }
}

public class MerchantViewModel
{
    public List<MerchantModel> Merchants { get; set; }
}
public class DefaultController : Controller
{
    // GET: Default
    public ActionResult Index()
    {
        var merchant1 = new MerchantModel
        {
            AppId = 1,
            Name = "Bob"
        };
        var merchant2 = new MerchantModel
        {
            AppId = 2,
            Name = "Ted"
        };
        var merchant3 = new MerchantModel
        {
            AppId = 3,
            Name = "Alice"
        };

        List<MerchantModel> list = new List<MerchantModel>();
        list.Add(merchant1);
        list.Add(merchant2);
        list.Add(merchant3);

        var model = new MerchantViewModel
        {
            Merchants = list
        };

        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MerchantViewModel model)
    {
        return View(model);
    }
}
@model TestCheckBoxes.Models.MerchantViewModel

    @{
        Layout = null;
    }

    <!DOCTYPE html>

    <html>
    <head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
        <form action="/default/index" method="post">
            <table>
                @for (int i = 0; i < Model.Merchants.Count; i++)
                {
                    <tr>
                        <td>
                            @Html.CheckBoxFor(x => x.Merchants[i].IsSelected)
                        </td>
                        <td>
                            @Html.HiddenFor(x => x.Merchants[i].AppId)
                            @Model.Merchants[i].AppId
                        </td>
                        <td>
                            @Html.HiddenFor(x => x.Merchants[i].Name)
                            @Model.Merchants[i].Name
                        </td>
                    </tr>
                }
            </table>

            <button type="submit">Submit</button>
        </form>



    </div>
</body>
</html>

Back in your [HttpPost] method in your controller, you will have a list of MerchantModel's with the bool value either true or false. This way you can check if it's true and just grab the AppId from there.

Is there any way to apply "Data Annotations for Model Validation" in for all check-boxes?

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

c# - In MVC/Razor, how do I get the values of multiple checkboxes and ...

c# asp.net-mvc asp.net-mvc-4 razor checkbox
Rectangle 27 6

Try passing a ViewModel into your page, and using the model binder to post the same view model back into your controller

public class MerchantModel
{
    public int AppId { get; set; }
    public string Name { get; set; }
    public bool IsSelected { get; set; }
}

public class MerchantViewModel
{
    public List<MerchantModel> Merchants { get; set; }
}
public class DefaultController : Controller
{
    // GET: Default
    public ActionResult Index()
    {
        var merchant1 = new MerchantModel
        {
            AppId = 1,
            Name = "Bob"
        };
        var merchant2 = new MerchantModel
        {
            AppId = 2,
            Name = "Ted"
        };
        var merchant3 = new MerchantModel
        {
            AppId = 3,
            Name = "Alice"
        };

        List<MerchantModel> list = new List<MerchantModel>();
        list.Add(merchant1);
        list.Add(merchant2);
        list.Add(merchant3);

        var model = new MerchantViewModel
        {
            Merchants = list
        };

        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MerchantViewModel model)
    {
        return View(model);
    }
}
@model TestCheckBoxes.Models.MerchantViewModel

    @{
        Layout = null;
    }

    <!DOCTYPE html>

    <html>
    <head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
        <form action="/default/index" method="post">
            <table>
                @for (int i = 0; i < Model.Merchants.Count; i++)
                {
                    <tr>
                        <td>
                            @Html.CheckBoxFor(x => x.Merchants[i].IsSelected)
                        </td>
                        <td>
                            @Html.HiddenFor(x => x.Merchants[i].AppId)
                            @Model.Merchants[i].AppId
                        </td>
                        <td>
                            @Html.HiddenFor(x => x.Merchants[i].Name)
                            @Model.Merchants[i].Name
                        </td>
                    </tr>
                }
            </table>

            <button type="submit">Submit</button>
        </form>



    </div>
</body>
</html>

Back in your [HttpPost] method in your controller, you will have a list of MerchantModel's with the bool value either true or false. This way you can check if it's true and just grab the AppId from there.

Is there any way to apply "Data Annotations for Model Validation" in for all check-boxes?

c# - In MVC/Razor, how do I get the values of multiple checkboxes and ...

c# asp.net-mvc asp.net-mvc-4 razor checkbox
Rectangle 27 5

The C syntax for declarations uses a model of Show us how you would use something and tell us what type that is.

Thus, if x is an int, we start with x and then say it is an int: int x;.

If x is a pointer to an int, then we would use *x to get an int, so we say int *x;.

If x is a function that returns an int, then we would use it as x() to get an int, so we say that is an int: int x();.

One reason for using this model is that it mostly uses the grammar you have already built for expressions: The body of the declaration gets parsed in the same way as expressions, and then you just tack on the type. If you do not use the same model, then you have to invent more grammar for declaring types.

This model makes declarations such as int *x, y; perfectly clear: Both *x and y have type int.

VERY interesting. I wish I could accept multiple answers, all are very telling. This design makes a lot of sense, though I would prefer it the other way. After all, how often does one have to declare different storage types (I think thats what its called) on the same type on the same line?

Not all that uncommonly, actually. A single declaration line may be used for a complex multilayered type and for the simpler subtypes that are extracted from it. Of course Best Practice is actually to use typedefs to build up anything really complicated in stages, which gives you the intermediate typedefs as a free bonus.

BTW, good job of illustrating that relationship, Eric. I mentioned it in passing, but you've called it out and made it clearer.

I hate this design philosophy, but I'm glad someone explained it as a general rule. +1

c - Placement of [] and * - Stack Overflow

c pointers