MVC HTTP Post输入返回null

时间:2016-05-10 01:57:58

标签: asp.net-mvc

控制器:

public class signindua extends AppCompatActivity {
int REQUEST_CAMERA = 0, SELECT_FILE = 1;
Button btnSelect;
ImageView imageView;
Bitmap bmNormal, bmGrayScale, bm, bitmap_Source;

// ImageView ivImage;

//layout dari button sebelumnya//
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.signindua);

    btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
    imageView = (ImageView) findViewById(R.id.imageView);
    btnSelect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImage();
        }
    });
}

private void selectImage() {
    final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
    AlertDialog.Builder builder = new AlertDialog.Builder(signindua.this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, REQUEST_CAMERA);
            } else if (items[item].equals("Choose from Library")) {
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(
                        Intent.createChooser(intent, "Select File"),
                        SELECT_FILE);
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == REQUEST_CAMERA) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
            File destination = new File(Environment.getExternalStorageDirectory(),
                    System.currentTimeMillis() + ".jpg");
            FileOutputStream fo;
            try {
                destination.createNewFile();
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            imageView.setImageBitmap(thumbnail);
        } else if (requestCode == SELECT_FILE) {
            Uri selectedImageUri = data.getData();
            String[] projection = {MediaStore.MediaColumns.DATA};
            CursorLoader cursorLoader = new CursorLoader(this, selectedImageUri, projection, null, null,
                    null);
            Cursor cursor = cursorLoader.loadInBackground();
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
            cursor.moveToFirst();
            String selectedImagePath = cursor.getString(column_index);
            Bitmap bm;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(selectedImagePath, options);
            final int REQUIRED_SIZE = 200;
            int scale = 1;
            while (options.outWidth / scale / 2 >= REQUIRED_SIZE
                    && options.outHeight / scale / 2 >= REQUIRED_SIZE)
                scale *= 2;
            options.inSampleSize = scale;
            options.inJustDecodeBounds = false;
            bm = BitmapFactory.decodeFile(selectedImagePath, options);
            imageView.setImageBitmap(bm);
        }
    }
}
//-------don't know-----//
/*
    bitmap_Source = BitmapFactory.decodeResource(getResources(), R.drawable.kamera);
    imageView.setImageBitmap(getGrayscale_ColorMatrixColorFilter(bitmap_Source));
*/
private Bitmap selectedImagePath (Bitmap src){
        int width = src.getWidth();
        int height = src.getHeight();

        Bitmap dest = Bitmap.createBitmap(width, height,
                Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(dest);
        Paint paint = new Paint();
        ColorMatrix colorMatrix = new ColorMatrix();
        colorMatrix.setSaturation(0); //value of 0 maps the color to gray-scale
        ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix);
        paint.setColorFilter(filter);
        canvas.drawBitmap(src, 0, 0, paint);

        return dest;
    }
}

查看:

public ActionResult MyController()
{
    ViewBag.DateNow = DateTime.Now.ToString("yyyy-MM-dd");
}

[HTTPPost]
public ActionResult MyController(string fromDate)
{
    ViewBag.DateNow = fromDate;
}

我想要实现的是在POST之前传递给ViewBag.DateNow的数据是当前日期并且它成功地引入视图。但是,当我尝试用(例如: 2016-05-10 )填写输入表单并单击“搜索”按钮时。但似乎fromDate字符串返回 NullReferenceException 。我正在网上尝试一些解决方案,但我仍然无法做到正确,这就是我决定将其发布的原因。提前谢谢!

2 个答案:

答案 0 :(得分:2)

试试这个:

1)替换为[HttpPost]而不是[HTTPPost]

2)你应该添加name =" "输入如下:

 <input id="fromDate" name="fromDate" type="text" class="datepicker" />

答案 1 :(得分:2)

为了使其正常工作,您需要在name中指定textbox属性。它必须与HTTP post操作方法中的输入变量具有相同的值,即fromDate。目前,id属性设置为fromDate

<input id="fromDate" name="fromDate" type="text" value="@ViewBag.DateNow" />

如果您未指定此name属性,那么当您发布表单时,fromDate始终为null。像上面那样指定它将确保fromDate始终具有值(如果输入)。

我想在这里偏离主题,我建议你使用view models来提交表单。您可以将视图模型作为输入参数,而不是在操作方法中使用单独的输入变量。

我写了一个关于这里的视图模型的答案,如果你有时间,请去阅读:

What is ViewModel in MVC?

根据您的示例,我将拥有一个只包含一个属性的视图模型,即FromDateFromDate将包含文本框中的值。它设置为string,因为您想要传递格式化的日期值:

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

此值将在HTTP get操作方法中设置,视图模型将发送到视图:

public ActionResult Index()
{
     TestModel model = new TestModel();
     model.FromDate = DateTime.Now.ToString("yyyy-MM-dd");

     return View(model);
}

在您的视图中,您将接受此视图模型并相应地创建表单:

@model WebApplication_Test.Models.TestModel

@using (Html.BeginForm())
{
     @Html.TextBoxFor(m => m.FromDate)
     <button type="submit">Search</button>
}

提交此表单时,您需要HTTP post操作方法来处理提交。由于视图绑定到视图模型,因此操作方法将接受它作为输入参数:

[HttpPost]
public ActionResult Index(TestModel model)
{
     // Do what you need to do
     string date = model.FromDate;

     return View(model);
}

你的做法也是正确的。我刚给你看了另一种方法。有一天,你可能会有一个包含许多输入值的巨大形式,那么我的方法将是“更清洁”。