Passing variables with POST in ASP.NET MVC

前端 未结 2 1635
刺人心
刺人心 2021-02-14 20:11

I am trying to pass a string variable inside asp.net MVC. I use breakpoints so I see that it does go to the correct method in the controller, but the variables posted are equal

2条回答
  •  醉酒成梦
    2021-02-14 20:24

    On a slightly separate note there is nothing wrong with passing variables like you are, but a more efficient way would be to pass around a strongly typed view model allowing you to take advantage of many aspects of MVC's goodness:

    • strongly-typed views
    • MVC Model Binding
    • Html Helpers

    Create a new view model:

    public class TestModel
    {
        public string TestInput { get; set; }
    }
    

    Your test controller:

        [HttpGet]
        public ActionResult TestForm()
        {
            return View();
        }
    
        [HttpPost]
        public ActionResult TestForm(FormCollection collection)
        {
            var model = new TestModel();
            TryUpdateModel(model, collection);
    
            Response.Write("[" + model.TestInput + "]");
    
            return View();
        }
    

    Your view:

    @model .Models.TestModel
    
    @{
        Layout = null;
    }
    
    
    
    
    
        TestForm
    
    
        
    @using(Html.BeginForm()) {
    @Html.LabelFor(m => m.TestInput)
    @Html.TextBoxFor(m => m.TestInput)
    }

提交回复
热议问题